Is there a way to create "stored procedure" in mongodb?
I know mongodb has serverside javascript. But It's different, I don't think server side function is able to call collection. For example if I have following example.
mycollection1.findOne({_id: id}, function(err, result1){
mycollection2.findOne({_id: result1.id}, function(err, result2){
mycollection3.findOne({_id: result2.id}, function(err, result3){
return {};
});
});
});
mycollection1.findOne({_id: id}, function(err, result1){
mycollection2.findOne({}, function(err, result2){
mycollection3.findOne({}, function(err, result3){
var someDataToDisplayToUI =
{
data1 : result1,
data2: result2,
data3: result3
};
return someDataToDisplayToUI;
});
});
});
I'm using mongoose from express.js server, currently mongoose call three times of above example. Is there a way to call once?
MongoDB doesn't support queries spanning multiple collections. There's no way around it. You have to make multiple queries at the application level. What you are doing seems to be the way to go. That is the pitfall of non-relational database. Maybe if you need to make these calls frequently, you would be better off with a relational database or it would be good to reconsider your schemas.
MongoDb isn't relation friendly. But as you are using mongoose, if you have any relationships, you can have references in documents across multiple collections and use a neat option called populate which fetches data from other collections.
Still mongoose will internally make two mongo queries
. This option makes defining relationships a whole lot easier.
Check the docs.
Populate can't be used for more than one level at a time.
mycollection1.findOne({_id: id}).populate('id',null,','<Collection2 Model Name>',function(err,result1){
//result1.id will be your result2 in the question instead of an id
result1.id.populate('id.id',null,'<Collection3 Model>',function(err,result){
//result1.id.id is now your result3 in the question
})
});