以下是用户模型,帖子模型和路线的代码。我需要查询数据库,然后通过路由器传递给视图。我错过了什么?
用户模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
帖子模特:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new Schema({
postTitle: {
type: String,
required: true
},
postStory: {
type: String
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
module.exports = mongoose.model('Post', postSchema);
这是我正在尝试的路由器中的查询,但显然它不是要走的路......
我的GET路线:
router.get('/dashboard', isLoggedIn, function(req, res) {
Post.find({author:req.user._id}, (err, posts) => {
if(err) {
console.log(err);
} else {
res.render('users/dashboard', {currentUser: req.user, posts: posts});
}
});
});
我在这里缺少什么?
答案 0 :(得分:1)
您可能希望更改find
查询以匹配以下行中的正确属性:
Post.find({author: req.user._id}, (err, posts) => {
是:
Post.find({'author.id': req.user._id}, (err, posts) => {
了解详情:http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html