2017-10-04 33 views
0

这样做的目的是从一个机柜具有指定名称(在这种情况下,“倩碧托托”)获取类型文秘的职业和我挣扎在这里。聚集问题与2个集

驾驶室型号:

var cabinet = new cabModel({ 
_id: new mongoose.Types.ObjectId(), 
InfoCab:{Nom: "Clinique Toto"} //This is the Name of the Cabinet 
}); 

cabinet.save((err, cabinet) => { 

PRO MODEL

var pro1 = new proModel({ 
    _id: new mongoose.Types.ObjectId(), 
    Nom: 'ProTITI', 
    Cv:{ Fonction: { Secretaire: false}} 
}); 

pro1.Cabinets.push(cabinet._id); 
pro1.save((err, cabinet) => { }); 

var pro2 = new proModel({ 
    _id: new mongoose.Types.ObjectId(), 
    Nom: 'Pro_TOT', 
    Cv:{ Fonction: { Secretaire: true}} 
}); 

设置写字台:适用于某些利弊的。创建进入驾驶室

pro2.Cabinets.push(cabinet._id); 
pro2.save((err, cabinet) => { }); 

var pro3 = new proModel({ 
    _id: new mongoose.Types.ObjectId(), 
    Nom: 'Josianne', 
    Cv:{ Fonction: { Secretaire: true}} 
}); 
pro3.Cabinets.push(cabinet._id); 
pro3.save((err, cabinet) => { }); 

推优点。

cabinet.Pro.push(pro1, pro2, pro3); 
cabinet.save(); 

console.log("Done"); 
}); 

const handleError = function (err) { 
console.error(err); 
}; 

我得到这个至今:

db.Pro.aggregate([ 
{ 
    $match: { 
     Cv: { 
      Fonction: { 
       Secretaire: true 
      } 
     } 
    } 
}, 
{ 
    $lookup: 
    { 
     from: "Cab", 
     localField:"Nom", 
     foreignField: "_id", 
      as: "PK" 
    } 
} 
]) 

以下是架构: 临架构:

const ProSchema = new Schema({ 
_id: { type: Schema.Types.ObjectId }, 
Cv: {Fonction: {Pro: {type: Boolean,}, 
       Secretaire: {type: Boolean} 
    } 
} 

CabSchema:

const CabSchema = new Schema({ 
Pro: [{ type: Schema.Types.ObjectId, ref: 'ProSchema' }], 
InfoCab: { 
     Nom: {type: String} 
}); 

回答

0

你可以添加架构为您的模型,以便你的问题有更多的澄清。

从给定的信息,它看起来像喃是一个字符串,即Nom: 'Josianne'你如下使用查找:

$lookup: 
{ 
    from: "Cab", 
    localField:"Nom", 
    foreignField: "_id", 
    as: "PK" 
} 
  1. 现在的问题是_idObjectId()类型,这是一个散列字符串唯一生成,其中Nom是由您创建的字符串,逻辑上它们将永远不匹配。
  2. 的iF Cab集合是相同cabModel的foreignField应该InfoCab.Nom。即foreignField: "InfoCab.Nom",

=== UPDATE ===观察

夫妇可能会瓦纳考虑:

  1. 你应该使用聚合如下:proModel.aggregate([...])
  2. 如果您已经使用ref在你的猫鼬架构,您可以使用.populate()方法。
+0

我刚刚编辑了模式, 干杯, – NelieluTu

+0

你试过#2吗? – imixtron

+0

这是infocab的输出。nom:{“_id”:ObjectId(“59d4b229585ee41a309ade51”),“Nom”:“Josianne”,“Cv”:{“Fonction”:{“Secretaire”:true}}“Cabinets”:[ObjectId(“59d4b229585ee41a309ade4e” )“__v”:0,“PK”:[]} {“_id”:ObjectId(“59d4b229585ee41a309ade50”),“Nom”:“Pro_TOT”,“Cv”:{“Fonction”:{“Secretaire” :true}},“Cabinets”:[ObjectId(“59d4b229585ee41a309ade4e”)],“__v”:0,“PK”:[]} 这里的东西是我想要cab名称作为过滤器。 干杯, – NelieluTu