如何在mongoose中填充其他集合的子文档?

时间:2014-06-13 06:59:17

标签: node.js mongodb mongoose

ASchema = new mongoose.Schema({
  name: String,
  B: [BSchema]
});

var BSchema = new Schema({
  name: String
});

var CSchema = new Schema({
  name: String,
  B: {
    type: Schema.ObjectId,
    ref: 'BSchema'
  }
});

//This is OK, but not one time mongoose search:
CSchema.find({
    name: 'C_xxx'
  }).exec(function(err, docC) {

  docC.forEach(function(o) {
    var BId = o.B;
    ASchema.findOne({
        'B._id': BId
      }, {
        'B.$': 1
      }
      ).exec(function(err, docA) {
      var Bname = docA.B[0].name;
      var Cname = docA.name;
    });

  });
});

//wrong in populate:
CSchema.find({
    name: 'C_xxx'
  })
  .populate('ASchema.B')
  .exec(function(err, docC) {
  docC.forEach(function(o) {
    var Bname = o.B.name;
    //ERROR:o.B is a objectId,o.B.name is undefined
    //Aname can't find
  });
});

我用populate找不到它, o.B是objectId,o.B.name是未定义的

BSchema是ASchema的子文档,CSchema具有BSchema的ref连接。

这样的数据:

ASchema = {
  name: "A_xxx",
  B: [{
      _id: 1,
      name: "B_xxx"
    }, {
      _id: 2,
      name: "B_xxx"
    }]
}
CSchema = [{
    name: "C_xxx",
    B: 1
  }, {
    name: "C_xxx",
    B: 2
  }]

我想找到所有CSchema,CSchema的名字是“c_xxx”,并显示CSchema的B名称和A的名字。

喜欢这个结果:{CName:“c_xxx”,BName:“b_xxx”,AName:“a_xxx”}

0 个答案:

没有答案