mongoose怎么populate别的集合的子文档?
发布于 8个月前 作者 gclsoft 541 次浏览
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;
    A.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
  });
});

I can’t find it with populate, o.B is a objectId,o.B.name is undefined.

BSchema is a subdocument of ASchema, CSchema has a ref connection of BSchema.

Data like this:

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
  }]

I want to find all CSchema which CSchema’s name is "c_xxx", and shows CSchema’s B’s name and its A’s name.

Like this result: {CName:"c_xxx",BName:"b_xxx",AName:"a_xxx"}

2 回复

CSchema.find().populate(‘B’).exec();

CSchema.find().populate('B’, ‘name’).exec();

我很好奇,既然都能用英文提问,为何不用英文搜索?或者看文档?

B没有单独保存到一个集合里, 是A的子文档, 所以你那样是找不到的 我本来是写成CSchema.find().populate(‘A.B’),但是也不行

回到顶部