![](/img/trans.png)
[英]How to populate document nested in array of objects in Mongoose?
[英]How to populate nested objects asynchronously in mongoose?
我在猫鼬的人口中挣扎。 假设我有一个包含许多嵌套对象的大型文档,这些对象并非总是具有Schemas或只是Type.Mixed。
该文档的架构如下所示:
{
token: String,
group: String,
connectionStatus: String,
activeQuestLine: String,
quests:
{
exposition: [
{
content: { type: mongoose.Schema.Types.ObjectId, ref: 'Quest' },
status: String,
trigger:
{
name: String,
param: mongoose.Schema.Types.Mixed
},
subQuests:
[
{
content: { type: mongoose.Schema.Types.ObjectId, ref: 'Quest' },
status: String,
trigger:
{
name: String,
param: mongoose.Schema.Types.Mixed
}
}
]
}
],
conflict: [
{
content: { type: mongoose.Schema.Types.ObjectId, ref: 'Quest' },
status: String
}
],
resolution: [
{
content: { type: mongoose.Schema.Types.ObjectId, ref: 'Quest' },
status: String
}
]
},
inventory:
{
maxSlots: Number,
slots: [
{
itemType: String,
content: mongoose.Schema.Types.Mixed,
empty: Boolean
}
]
}
};
因此,我将一次“ findOne”这种类型的文档,将其保存,然后在需要时填充特定用例的某些部分。 就我所看到的关于该主题的大多数问题而言,是指在处理填充后的文档后将其保存,但是我想保持文档原样,仅将(填充的)数据传递给其他功能。
例如,我只想获取博览会属性的某个任务的所有“子任务”。 在那些也可以有其“ subQuest”的地方,是的,应该有一个递归模式,但是目前这不是主要问题。 问题是我想像这样迭代它:
async.forEachSeries(
questInfo.subQuests,
function (subQuestInfo, eachCallback)
{
QuestManager.getQuest(subQuestInfo.content, function (subQuest)
{
if (!subQuest) throw 'SubQuest ' + subQuestInfo.content + ' not found';
subQuestInfo.content = subQuest;
eachCallback();
});
},
function (err)
{
if (err) throw err;
activeQuests.push(questInfo);
});
从主文档中提取questInfo并将其作为参数传递给该功能。 但在这一行:
subQuestInfo.content = subQuest;
“内容”的值仍然只是ObjectId,因此是先前的值。 我的任务显然没有任何影响! 这是一种人工尝试,是否有更好的方法来解决?
感谢您的时间。
假设您有一个带有quest.subQuests成员的Quest模式,我将像这样去做:
Quest.methods.getSubQuests = function(done) {
var getSubQuestFns = this.subQuests.map(function(subQuest) {
return QuestManager.getQuest.bind(QuestManager, subQuest.content)
})
async.parallel(getSubQuestFns, done)
}
// get some Quest instance
quest.getSubQuests(function(err, subQuests) {
// whatever
})
(这不会修改原始任务文档。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.