我正在努力使用Mongoose / NodeJS来获取我想要的数据。让我解释一下这个场景:
我有一组负载,一组运营商和一组客户。这些负载可以由一个或多个载波承载,我想按载波列出负载。每个客户都有自己的运营商,可以与其他客户共享。我有3个集合(为了理解而简化):第一个是users
,也用于身份验证。当客户登录系统时,他知道自己的AccountID:
{
"Name" : "Customer",
"AccountID" : ObjectId("52a704ff4ae2d0f00a00000c"),
"Role" : "Customer"
}
{
"Name" : "Carrier 1",
"AccountID" : ObjectId("52a7057d4ae2d0f00a00000e"),
"Role" : "Carrier"
}
{
"Name" : "Carrier 2,
"AccountID" : ObjectId("52a705e54ae2d0f00a000010"),
"Role" : "Carrier"
}
第二个是customercarrier
,表明哪个运营商属于哪个客户:
{
"OwnerID" : "52a704ff4ae2d0f00a00000c",
"CarrierID" : "52a7057d4ae2d0f00a00000e",
}
{
"OwnerID" : "52a704ff4ae2d0f00a00000c",
"CarrierID" : "52a705e54ae2d0f00a000010",
}
第三个是loads
的集合。每个负载都可以由一个或多个运营商承载,其ID在Instances.Assignees.AssigneeID
上分配:
{
"LoadNumber" : 1,
"Instances" : [
{
"_id" : ObjectId("52bda0144ce315980d000015"),
"OwnerID" : "52a704ff4ae2d0f00a00000c",
"OwnerName" : "Customer 1",
"Assignees" : [
{
"AssigneeID" : "52a7057d4ae2d0f00a00000e",
"AssigneeName" : "Carrier C1",
"_id" : ObjectId("52bd9ffc4ce315980d00000d"),
}
]
}
]
}
{
"LoadNumber" : 2,
"Instances" : [
{
"_id" : ObjectId("52bd9ffc4ce315980d00000f"),
"OwnerID" : "52a704ff4ae2d0f00a00000c",
"OwnerName" : "Customer 1",
"Assignees" : [
{
"AssigneeID" : "52a705e54ae2d0f00a000010",
"AssigneeName" : "Carrier C2",
"_id" : ObjectId("52bd9ffc4ce315980d000010"),
}
]
}
]
}
{
"LoadNumber" : 3,
"Instances" : [
{
"_id" : ObjectId("52bda02c4ce315980d00001b"),
"OwnerID" : "52a704ff4ae2d0f00a00000c",
"OwnerName" : "Customer 1",
"IncomingStatus" : null,
"Assignees" : [
{
"AssigneeID" : "52a7057d4ae2d0f00a00000e",
"AssigneeName" : "Carrier C1",
"_id" : ObjectId("52bda02c4ce315980d00001c"),
},
{
"AssigneeID" : "52a705e54ae2d0f00a000010",
"AssigneeName" : "Carrier C2",
"_id" : ObjectId("52bda02c4ce315980d00001f"),
}
]
}
]
}
我想列出承运人的负载,如下:
Carrier C1:
Load 1
Load 3
Carrier C2:
Load 2
Load 3
我尝试使用以下代码,但我正在努力应对回调。我试图在最外层循环之后放回调,但在这种情况下,它什么也不返回。在最里面之后,它在第一次循环迭代后返回:
this.model('customercarrier').find({ "OwnerID" : accountID }, {}, {}, function(err, rst) {
if (!err) {
if(rst.length != 0){
var rstret = [];
for (var i = 0; i < rst.length; i++) {
var searchObj = { "Instances.Assignees" : { $elemMatch : { AssigneeID : rst[i].CarrierID } } } ;
this.model('load').find(searchObj, { }, { }, function(err, results) {
if (!err) {
for (var x = 0; x < results.length; x++) {
var myInstance = _.find( results[x].Instances, function( el ) {
return el.OwnerID === accountID;
} );
rstret.push(results);
}
} else {
cb(err,results);
}
});
}
cb(err,rstret);
}
else{
cb(err,[]);
}
}
else{
console.log("Error while retrieving carriers");
}
});
我知道这是带回调的异步函数的预期行为,但我需要之前写过的那种行为,但我无法理解。 NodeJS中的Mongoose可以实现吗?
非常感谢你!非常感谢任何想法!