现在,我正在从事社交媒体项目,用户可以轻松地对帖子发表评论并发表评论。但是,当我发送查找与用户评论相关的帖子的请求时,并不会相应填充该信息。
帖子模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema({
text: {
type: String,
required: [true, 'Name is required']
},
photo: {
data: Buffer,
contentType: String
},
likes: [{ type: mongoose.Schema.ObjectId, ref: 'User' }],
comments: [
{
text: String,
created: { type: Date, default: Date.now },
postedBy: { type: mongoose.Schema.ObjectId, ref: 'User' }
}
],
postedBy: { type: mongoose.Schema.ObjectId, ref: 'User' },
created: {
type: Date,
default: Date.now
}
});
const Post = mongoose.model('Post', postSchema);
module.exports = Post;
这是此请求的相应控制器
exports.listPostByUser = (req, res, next) => {
Post.find({ postedBy: req.profile._id })
.populate('comments', 'text created')
.populate('comments.postedBy', '_id name')
.populate('postedBy', '_id name')
.exec((err, posts) => {
if (err) {
return res.status(400).json({
error: 'errorHandler.getErrorMessage(err)'
});
}
res.json(posts);
});
};
当我登录 req.profile._id 时,它会正确找到userId,但不会填充注释。