1

I need to populate the comments based off of their ID's which are saved in another schema == Project as the array of comments.

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:

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 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

3 Comments

Ok please correct find Query with this --> Project.findById(new mongoose.Types.ObjectId(req.params.projectId)).populate('comments')
mongoosejs.com/docs/populate.html just check if you are missing something
Wait this worked! const comments = await Project.findById(new mongoose.Types.ObjectId(req.params.projectId)).populate('comments') Thanks !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.