pet*_*tur 0 javascript mongoose mongodb node.js
我在NodeJS中使用mongoose,我有一个来自子数组的id.我的模型定义如下:
var thingSchema = new schema({
thingId: String,
smallerThings : [smallerThingsSchema]
});
var smallerThingsSchema = new schema({
smallerThingId: String,
name : String,
anotherName : String
});
Run Code Online (Sandbox Code Playgroud)
我有smallerThingId,但我想得到thingId.
现在我有一个看起来像这样的for循环(我认为非常无效).潜在地,可能有100,000件事情.
//Find all things
thingModel.find({}, null, function (error, things) {
if (error) {
callback(error);
}
else {
//Go through all things
for(var i = 0; i < things.length; i++){
//check if a thing with the array of smaller things matches the id
for(var j = 0; j<things[i].smallerThings.length; j++){
if(things[i].smallerThings[j].id === smallerThingId){
//return it
return things[i];
}
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
感谢任何帮助或我可以在哪里(docs/blog/other)学习如何处理这种情况.
要按子文档ID获取文档,您可以使用以下代码:
thingModel.find({"smallerThings.smallerThingId":smallerThingId}, null, function (error, things) {
});
Run Code Online (Sandbox Code Playgroud)
这将返回具有"smallerThingId"的文档.