callmekatootie
callmekatootie

Reputation: 11228

MongooseJS - Retrieve all documents based on ObjectIds in an array

I am using MongooseJs with Express / Node.

I have a Schema like this:

ParentSchema = {  
    _id: ObjectID,
    children = [ObjectId]
}  

I have another Schema like this:

ChildSchema = {  
    _id: ObejctID,
    name: String
    age: Number
}

The _id in ChildSchema is basically stored in the children array of ParentSchema.
Now, my question is how to get the documents in the model of the ChildSchema when I have only their ObjectIds in the children. Basically, if children = [1, 2, 3, 4[, how do I fetch ALL the records from ChildSchema with _id in [1, 2, 3, 4]?

Upvotes: 0

Views: 273

Answers (1)

topek
topek

Reputation: 18979

The easiest way to achieve this is populate

Example:

ParentSchema = {  
    _id: ObjectID,
    children = [{type: Schema.Types.ObjectId, ref: "ChildModelName"}]
} 

ParentModel.find().populate("children").exec(cb);

Upvotes: 1

Related Questions