javascript - 引用另一个模型时,Mongoose 填充不起作用
问题描述
我一直在尝试在评论模型中引用用户模型。我已经确保一切都检查了,但它仍然无法正常工作。
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
}
]
}
解决方案
推荐阅读
- makefile - 用于检查拼写的 Makefile
- react-native - 警告:forwardRef 渲染函数只接受两个参数:props 和 ref。您是否忘记使用 ref 参数?本机基础
- c# - System.ArgumentException: 'myObject' 类型的对象无法转换为'System.Collections.Generic.List`1[myObject]' 类型。
- bash - Bash jq 包含搜索键
- node.js - 我有多个相互引用的猫鼬模式。我正在使用 gql-compose-mongoose。如何将一个文档的 objectID 推送到另一个文档中?
- c# - 在其视图模型(Prism WPF)中动态加载用户控件和设置属性
- solr - 如何通过管理 API 创建 Solr 核心而不使用配置文件创建实例目录?
- google-cloud-vision - Cloud Vision API 是否有办法获取键值对作为响应,就像他们的 AWS Textract 对应物一样?
- php - Laravel 计划在 Windows 中使用任务计划不工作
- javascript - Phaser 3 如何用颜色填充 Phaser.Curves.Path?