I have a mongodb collection and I want to populate a nested field when I return data from the database. I want to return only specific fields, the code below with explain more.
this is my schema
const hallSchema = new Schema({
hallName: { type: String, required: true },
email: { type: String, required: true },
images: [{ type: String, required: true }],
});
and this is code I'm writing to get the first image of the images array
chatRooms = await ChatRoom.find({ _id: convertedIds })
.populate("hallId", `hallName ${images[0]}`);
the query above is failing because it is invalid, how can I get the first item of images array? Thanks for any help
CodePudding user response:
What I understand is that you want to populate data in hallId and from populated hallId data you want to select the first image from the images array. So to project fields from populated data you can do this, It works for me,
const chatRooms = await ChatRoom.find({ _id: convertedIds })
.populate({ path: 'hallId', select: {
hallName: 1,
images: { $slice: ['$images', 1] },
}
});