Reputation: 1471
T his is my scheme, I want to do a single query
and obtain all documents
and all objects's documents.
var CureSchema = mongoose.Schema({
id: Number,
therapist: {type:mongoose.Schema.Types.ObjectId, ref:'User'},
supervisor: {type:mongoose.Schema.Types.ObjectId, ref:'User'},
parents: {type:mongoose.Schema.Types.ObjectId, ref:'User'},
children: {type:mongoose.Schema.Types.ObjectId, ref:'Child'},
startate : Date,
endDate : Date,
deleted: Boolean,
});
var Cure = mongoose.model('Cure', CureSchema);
if i use the normal query, i'have objectId
in the output.
{
"id":0, "therapist":ObjectId("5253cbd8d4fb240000000007"), "supervisor":ObjectId("5253cc9fd4fb24000000000b"), "parents":ObjectId("5253cbdfd4fb240000000008"), "children":ObjectId("5253cb31d4fb240000000001"), "deleted":false, "startate": ISODate("2013-10-08T09:13:06.771Z"), "_id":ObjectId("5253cca2d4fb24000000000c"), "__v":0
}
Upvotes: 3
Views: 2002
Reputation: 4678
You can also use aggregate with a $lookup
Cure.aggregate([
{
"$lookup": {
"from": "users",
"localField": "therapist",
"foreignField": "_id",
"as": "therapist"
}
},
{
"$lookup": {
"from": "users",
"localField": "supervisor",
"foreignField": "_id",
"as": "supervisor"
}
}, ...
])
Upvotes: 0
Reputation: 14953
Technically it's not possible to do it with one query in mongodb, as the documents belong to three different collections. Mongoose will probably have to do five queries (although I think three should be enough but I'm not sure how smart Mongoose is).
However if what you're really asking is how do get the subdocuments using only one mongoose instruction, you should look to populate().
Cure.find()
.populate('therapist')
.populate('supervisor')
.populate('parents')
.populate('children')
.exec(resultHandler);
Upvotes: 3