MongoDB,在数组中填充嵌套对象



我有一个问题…我有一个这样的模式:

const chatSchema = new Schema({
[...]
title: {
type: String,
required: true
},
message: [
{
content: {
type: String,
required: true
},
creator: {
type: mongoose.Types.ObjectId,
required: true,
ref: 'User'
}
}
],
[...]
});

在我的Node后端,我怎么能访问我的创造者实例在我的消息数组?我不知道如何写查询填充…

谢谢大家!: -)

使用以下命令:

…在导入chatSchema为maybe chats后

module.exports.populateCreator = (req, res) => {
chats.findOne({chatID})
.populate({
path: 'message',
populate: {
path: "creator"
}
})
.then(chats => res.json(chats))
}

可以这样使用

Chats.find(query)
.populate({ 
path: 'message',
populate: {
path: 'creator'
} 
})
.exec(function(err, docs) {});

您要查找的查询是:

https://mongoplayground.net/p/2dpeZWsXR-V

db.booking.aggregate([
{
"$match": {
id: "61fdfeef678791001880da25"
}
},
{
$unwind: "$cart"
},
{
"$lookup": {
"from": "products",
"localField": "cart.product",
"foreignField": "id",
"as": "prod"
}
},
{
"$unwind": "$prod"
},
{
"$project": {
id: 1,
status: 1,
cart: [
{
id: "$cart.id",
date: "$cart.date",
timeSlots: "$cart.timeSlots",
product: {
id: "$prod.id",
name: "$prod.name",

}
}
],

}
}
])

最新更新