我一直在尝试在评论模型中引用用户模型。我已确保一切都已检查完毕,但仍然无法正常工作。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const commentSchema = mongoose.Schema({
writer: {
type: Schema.Types.ObjectId,
ref: 'User'
},
postId: {
type: String,
},
responseTo: {
type: Schema.Types.ObjectId,
ref: 'User'
},
content: {
type: String
}
}, { timestamps: true })
const Comment = mongoose.model('Comment', commentSchema);
module.exports = { Comment }
我在这里引用用户模型是因为我需要从中获取一些字段。
router.post("/saveComment", auth, (req, res) => {
const comment = new Comment(req.body)
comment.save((err, comment) => {
if (err) return res.json({ success: false, err })
//send newly saved comment inside parent cmp
Comment.find({ '_id': comment._id })
.populate('writer')
.exec((err, result) => {
if (err) return res.json({ success: false, err })
return res.status(200).json({ success: true, result })
})
})
})
向该端点发出请求会返回结果,但会忽略我对用户模型的引用
{
"success": true,
"result": [
{
"_id": "60527698499c27244c9e9f4c",
"content": "Comment 1",
"createdAt": "2021-03-17T21:37:28.463Z",
"updatedAt": "2021-03-17T21:37:28.463Z",
"__v": 0
}
]
}