2017-04-21 42 views
0

我有以下模式:如何填充由Mongoose中的composite _id引用的字段?

var WorkSchema = new Schema({ 
    _id:   Object, // {client: String, project: Number} 
    title:   String, 
    description: String 
}); 

var TimeWorkedSchema = new Schema({ 
    _id:   Object, // {client: String, date: Date} 
    work:   {type: Object, ref: 'Work'}, // {client: String, proyect: Number} 
    hours:   Number, 
    description: String 
}); 

var w = mongoose.model('Work', WorkSchema); 
var tw = mongoose.model('TimeWorked', TimeWorkedSchema); 

字段Work._idTimeWorked.work是具有相同属性的比较的对象。然后,我想填充TimeWorked模型与相应的工作数据和往常一样:

tw.find().populate('work').exec(function(err, res){ 
    console.log(res); 
}); 

打印:

[{ 
"_id": { 
    "client": "clientX", 
    "date": "2017-04-20T00:00:00.000Z"}, 
"work": { 
    "_id":{      ┐ 
     "client": "clientX", | 
     "project": 1},   | invariable 
    "title": "ABC",    | 
    "description": "defgh"}, ┘ 
"hours": 4, 
"description": "bored" 
},{ 
"_id": { 
    "client": "clientY", 
    "date": "2017-04-15T00:00:00.000Z"}, 
"work": { 
    "_id":{      ┐ 
     "client": "clientX", | 
     "project": 1},   | invariable 
    "title": "ABC",    | 
    "description": "defgh"}, ┘ 
"hours": 8, 
"description": "funny" 
},{...etc...} 
] 

正如你可以看到,在所有返回的对象,在人口work场是相同的目的。

但是,如果我删除填充方法(tw.find().exec(...)),我会得到原始work字段,它们实际上是不同的。

我认为猫鼬还没有实施这种类型的人口。我如何将两个模式联系起来以在查询中获取组合数据?

回答

1

docs

注:物件,数字,字符串,和缓冲区有效用作参考文献。

你需要这个$lookup

tw.aggregate({ 
     $lookup: 
     { 
      from: "works", // collection name 
      localField: "work", 
      foreignField: "_id", 
      as: "work" 
     } 
    }).exec(function(err, res){ 
    console.log(res); 
}); 
+0

感谢您的回答,但我得到了同样的结果。最后,我选择在单独的进程中选择初始查询中提到的所有Works,将它们逐个添加到HoursWorked(以旧式)。主要的问题是在一个需要关系数据库的项目中选择MongoDB(热衷于新颖性)。 – Rodrigo

+0

不客气,但这应该工作。如果你不介意的话,你应该分享你的查询。我测试了这个代码。如果您愿意,我可以添加测试数据。 – Veeram