如何在Mongoose中填充复合_id引用的字段?

时间:2017-04-21 01:09:40

标签: mongoose mongoose-populate

我有以下架构:

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字段,这些字段实际上是不同的。

我认为Mongoose没有实现这种类型的人口。如何将两个模式相关联以在查询中获取组合数据?

1 个答案:

答案 0 :(得分:1)

来自docs

  

注意:ObjectId,Number,String和Buffer可用作refs。

这个你需要$lookup

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