简体   繁体   English

Node + Mongoose:填充 ref 对象数组

[英]Node + Mongoose: Populate array of ref objects

I need to populate the comments based off of their ID's which are saved in another schema == Project as the array of comments.我需要根据他们的 ID 填充评论,这些 ID 作为评论数组保存在另一个模式 == Project中。

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

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

What do I want?我想要什么?

I want to populate and comments on a particular project.. This is what I am doing and it is returning null:我想对特定项目进行填充和评论。这就是我正在做的,它正在返回 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)
})

try this project schema试试这个项目架构

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

and use 'comments' while populating并在填充时使用“评论”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM