首页 > 解决方案 > Node + Mongoose:填充 ref 对象数组

问题描述

我需要根据他们的 ID 填充评论,这些 ID 作为评论数组保存在另一个模式 == 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' }
)}

我想要什么?

我想对特定项目进行填充和评论。这就是我正在做的事情,它返回 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.jsmongodbexpressmongoose

解决方案


试试这个项目架构

  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' }]
    });

并在填充时使用“评论”

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

推荐阅读