有没有办法创build一个“存储过程”调用多个查询在单个查询在mongodb(mongoose)
有没有办法在MongoDB中创build“存储过程”?
例如一个查询一次访问mongodb但实际调用多个集合(使用mongoose调用mongodb)
我知道mongodb有serverside javascript 。 但是不同的是,我不认为服务器端函数能够调用集合。 例如,如果我有下面的例子。
1.例子一(关系集合)
mycollection1.findOne({_id: id}, function(err, result1){ mycollection2.findOne({_id: result1.id}, function(err, result2){ mycollection3.findOne({_id: result2.id}, function(err, result3){ return {}; }); }); });
2.例子二(非关系集合)
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; }); }); });
我正在使用express.js服务器的mongoose,目前mongoose三次以上的例子。 有没有办法打一次?
MongoDB
不支持跨多个collections
查询。 这是没有办法的。 您必须在应用程序级别进行多个查询。 你在做什么似乎是要走的路。 这就是非关系数据库的缺陷。 也许如果你需要频繁地调用这些调用,那么关系数据库会更好,或者重新考虑你的模式是很好的。
MongoDb不友好。 但是,如果您使用的是mongoose
,如果您有任何关系,则可以跨多个集合在文档中引用它们,并使用称为“ populate
的整齐选项从其他集合中提取数据。
仍然mongoose会在内部做两个mongo查询
。 这个选项使定义关系变得更容易。
检查文档 。
填充不能用于一次超过一个级别。
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 }) });