Node +猫鼬:填充ref对象数组

时间:2020-09-01 12:43:26

标签: node.js mongodb express mongoose

我需要根据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)
})

1 个答案:

答案 0 :(得分: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' }]
    });

并在填充时使用“注释”

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