下面是User模型、Post模型和路由的代码。我需要查询数据库,然后通过路由器传递给 View 。我错过了什么?
用户模型:
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});
}
});
});
我在这里错过了什么?
最佳答案
您可能希望更改 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
关于node.js - 获取属于一个用户的所有帖子并显示以传递给 View Node/Express/Mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738972/