【问题标题】:Node + Mongoose: Populate array of ref objectsNode + Mongoose:填充 ref 对象数组
【发布时间】:2020-09-07 20:47:53
【问题描述】:

我需要根据他们的 ID 填充 cmets,这些 ID 作为 cmets 数组保存在另一个模式 == Project 中。

项目

const projectSchema = new mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
    title: { type: String, required: true },
    description: { type: String, required: true, minLength: 200, maxlength: 500 },
    // comments: { type: Array, default: [], ref: 'Comment' },
    comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
})

评论:

const commentSchema = new mongoose.Schema({
    comment: { type: String, required: true },
    project: { type: String, required: true, ref: 'Project' },
    user: { type: String, required: true, ref: 'User' }
)}

我想要什么?

我想在特定项目上填充和 cmets。这就是我正在做的事情,它返回 null:

router.get('/:projectId', currentUser, authenticate, async (req: Request, res: Response) => {
    // search the project 
    const project = await Project.findById(req.params.projectId).populate('comment')
    // return the populated comments 
    console.log('THE LIST OF PROJECT', project)  // <-------- null
    res.send(project)
})

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    试试这个项目架构

      const projectSchema = new mongoose.Schema({
          user: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
          title: { type: String, required: true },
          description: { type: String, required: true, minLength: 200, maxlength: 500 },
          comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
        });
    

    并在填充时使用“cmets”

    const project = await Project.findById(new mongoose.Types.ObjectId(req.params.projectId)).populate('comments')
    

    【讨论】:

    • 好的,请更正 find Query with this --> Project.findById(new mongoose.Types.ObjectId(req.params.projectId)).populate('comments')
    • mongoosejs.com/docs/populate.html 看看你是否遗漏了什么
    • 等这成功了! const comments = await Project.findById(new mongoose.Types.ObjectId(req.params.projectId)).populate('comments') 谢谢!!
    猜你喜欢
    • 2013-05-14
    • 2022-01-24
    • 2016-01-19
    • 2019-01-23
    • 2020-06-01
    • 2019-09-23
    • 2020-11-11
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多