Javascript 从id获取父对象,该id将对象子数组与NodeJS中的mongoose相匹配

Javascript 从id获取父对象,该id将对象子数组与NodeJS中的mongoose相匹配,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我在NodeJS中使用mongoose,我有一个来自子数组的id。I模型的定义如下: var thingSchema = new schema({ thingId: String, smallerThings : [smallerThingsSchema] }); var smallerThingsSchema = new schema({ smallerThingId: String, name : String, anotherName : Stri

我在NodeJS中使用mongoose,我有一个来自子数组的id。I模型的定义如下:

var thingSchema = new schema({
    thingId: String,
    smallerThings : [smallerThingsSchema]
});

var smallerThingsSchema = new schema({
    smallerThingId: String,
    name : String,
    anotherName : String
});
我有
smallerThingId
,但我想得到
thingId

现在我有一个类似这样的for循环(我想这是非常无效的)。可能会有10万件东西

//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];
                }
            }
        }
    }
});
//找到所有东西
thingModel.find({},null,函数(错误,事物){
如果(错误){
回调(错误);
}
否则{
//经历所有事情
for(var i=0;i对于(var j=0;j要按子文档id获取文档,可以使用以下代码:

thingModel.find({"smallerThings.smallerThingId":smallerThingId}, null, function (error, things) {

});

这将返回包含“smallerThingId”的文档。

您可以使用mongoose查找,如:

thingModel.find({"things.smallerThings.id": smallerThingId }, null, function (error, things) {
    if (error) {
        callback(error);
    }
    else {
        //do what you need
    }
});

这是行不通的。没有你所说的所谓“事物”。