koa2 mongoose 操作数据库时报错
发布于 7 年前 作者 zhaoxixiong 3944 次浏览 来自 问答

dao/post.js

let postModel = require('../db/models/post');
// 获取所有文章
let getPostAll = async () => {
  let postAll = await postModel.articles.find().sort({
    _id: -1
  }).exec();

};
module.exports = {
  getPostAll
}

model/post.js

let mongoose = require('../db');
let Schema = mongoose.Schema;
let postSchema = new Schema({
  title: {
    type: String
  },
  content: {
    type: String
  }
});
let postModel = mongoose.model('articles', postSchema);
module.exports = postModel;

db/db.js

const mongoose = require('mongoose');
const dbUrl = "mongodb://localhost/blog";
mongoose.connect(dbUrl);

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
  console.log("数据库连接成功!");
});
module.exports = mongoose

运行服务后,调用 getPostAll 方法时报错:

(node:32) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'find' of undefined
(node:32) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

通过 mongoose 的 model 操作数据库的方法 postModel.articles.find() 出错了,报 Cannot read property ‘find’ of undefined,这是为什么呢?

2 回复

postModel.articles.find()是什么操作啊,直接postModel.find()

postModel.find()

回到顶部