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)
})
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.