I'm working with mongoose in NodeJS and I have an id from a child array. I the models are defined like this:
var thingSchema = new schema({
thingId: String,
smallerThings : [smallerThingsSchema]
});
var smallerThingsSchema = new schema({
smallerThingId: String,
name : String,
anotherName : String
});
I have the smallerThingId
, but I want to get the thingId
.
Right now I have a for loop that looks like this (pretty ineffective I suppose). Potentially, there could be 100,000 things.
//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];
}
}
}
}
});
Grateful for any help or where I can look (docs/blog/other) to learn how to handle such scenario.
I'm working with mongoose in NodeJS and I have an id from a child array. I the models are defined like this:
var thingSchema = new schema({
thingId: String,
smallerThings : [smallerThingsSchema]
});
var smallerThingsSchema = new schema({
smallerThingId: String,
name : String,
anotherName : String
});
I have the smallerThingId
, but I want to get the thingId
.
Right now I have a for loop that looks like this (pretty ineffective I suppose). Potentially, there could be 100,000 things.
//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];
}
}
}
}
});
Grateful for any help or where I can look (docs/blog/other) to learn how to handle such scenario.
Share Improve this question asked May 26, 2016 at 12:09 peturpetur 1,3964 gold badges22 silver badges43 bronze badges2 Answers
Reset to default 6To get document by sub-document id you can use following code:
thingModel.find({"smallerThings.smallerThingId":smallerThingId}, null, function (error, things) {
});
This will return document having "smallerThingId".
You can use mongoose find like:
thingModel.find({"things.smallerThings.id": smallerThingId }, null, function (error, things) {
if (error) {
callback(error);
}
else {
//do what you need
}
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745101145a4611279.html
评论列表(0条)