有没有办法创建"存储过程"在mongodb?
我知道mongodb有serverside javascript。但它有所不同,我不认为服务器端功能可以调用收集。 例如,如果我有以下示例。
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;
});
});
});
我使用来自express.js服务器的mongoose,目前mongoose调用上述三次示例。有没有办法打电话一次?
答案 0 :(得分:2)
MongoDB
不支持跨多个collections
的查询。没有办法绕过它。您必须在应用程序级别进行多个查询。你正在做什么似乎是要走的路。这是非关系型数据库的缺陷。也许如果你需要经常进行这些调用,最好使用关系数据库,或者重新考虑你的模式会更好。
MongoDb不是友好关系。但是当您使用mongoose
时,如果您有任何关系,则可以在多个集合中的文档中引用,并使用称为populate
的简洁选项从其他集合中获取数据。
仍然mongoose将在内部进行两次mongo查询
。此选项使定义关系变得更加容易。
检查the docs。
Populate不能一次用于多个级别。
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
})
});