Reputation: 95
I have 2 collections namely eventPart and Participants.
eventPart:{
{
"_id" : ObjectId("5b62676ba5419449046a26c4"),
"rollNo" : "15K21A0528",
"eventName" : "Ebullienza",
"team" : 68,
"__v" : 0
},{
"_id" : ObjectId("5b62676ba5419449046a26c5"),
"rollNo" : "15G11A0518",
"eventName" : "Ebullienza",
"team" : 68,
"__v" : 0}
}
Participants : {
{
"_id" : ObjectId("5b62626d9306a610e36aca95"),
"rollNo" : "15S11A0528",
"name" : "Pavan Boro",
"email" : "[email protected]",
"mobile" : NumberLong(6700332950),
"branch" : "CSE",
"section" : "A",
"year" : 4
}, {
"_id" : ObjectId("5b62633d9306a610e36acae1"),
"rollNo" : "15S11A0518",
"name" : "Manoj",
"email" : "[email protected]",
"mobile" : NumberLong(9700332910),
"branch" : "CSE",
"section" : "A",
"year" : 4
}}
I want to query the database with eventName in eventPart along with data in Participant collection.
Ex: With eventName : 'Ebullienza' I want to fetch all the details that is related to eventName: 'Ebullienza' in Participants collection.
I have tried collecting the rollNo from eventPart and using it for in Participants collection. But I get stuck in collecting the rollNo in array
var rollNumber = new Array();
EventPart.find({'eventName':'Ebullineza'}).then(function(a){
a.forEach(function(roll){
rollNumber.push(roll.rollNo);
});
});
console.log(rollNumber); // prints [] - empty array
rollNumber is printed as [].
I think there could be a more efficient way of query 2 collections in mongoose.
Thanks.
Upvotes: 0
Views: 47
Reputation: 4678
print your array in the callback... otherwise he is printed before the end of execution of your find
var rollNumber = new Array();
EventPart.find({'eventName':'Ebullineza'}).then(function(a){
a.forEach(function(roll){
rollNumber.push(roll.rollNo);
});
console.log(rollNumber); // prints [] - empty array
});
Upvotes: 0
Reputation: 787
use $lookup
db.eventPart.aggregate([
{ "$match": { "eventName": "Ebullienza" } },
{
"$lookup": {
"from": "Participants",
"localField": "rollNo",
"foreignField": "rollNo",
"as": "Participants"
}
}
])
Upvotes: 1