gpt4 book ai didi

node.js - 同时填充多个字段

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:41 26 4
gpt4 key购买 nike

我有一个名为“聊天”的架构:

var ChatSchema   = new Schema({
vehicle: { type: Schema.Types.ObjectId, ref: 'Vehicle' },
messages: [String]
});

...以及另一个名为 Vehicle 的模式:

var VehicleSchema   = new Schema({
make: { type: Schema.Types.ObjectId, ref: 'Make' },
model: { type: Schema.Types.ObjectId, ref: 'Model' }
});

我需要一个填充车辆的查询,还需要填充车辆内部的“品牌”和“型号”字段。我尝试过这个但无法使其工作。也尝试过路径,但没有成功。

Chat.find(function (err, chats) {
if (err)
res.json({ success: false, response: err });

if (chats.length == 0)
res.json({ success: false, response: "Nothing found." });
else
res.json({ success: true, response: { chats: chats } });
}).populate('vehicle make model');

最佳答案

嵌套填充必须在单独的步骤中完成,这有点尴尬,但您可以使用如下方法来完成:

Chat.find().populate('vehicle').exec(function (err, chats) {
Make.populate(chats, 'vehicle.make', function (err, chats) {
ModelModel.populate(chats, 'vehicle.model', function (err, chats) {
if (err)
res.json({ success: false, response: err });

if (chats.length == 0)
res.json({ success: false, response: "Nothing found." });
else
res.json({ success: true, response: { chats: chats } });
});
});
});

文档 here .

关于node.js - 同时填充多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28183217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com