为什么填充在mongodb中返回空结果

时间:2019-05-04 17:42:28

标签: node.js mongodb mongoose

我想填充我的属性(subCategories),但是尽管我的数据库中有结果,但它返回空。我有错过什么吗?我遵循猫鼬的填充方法:

const Document = mongoose.model('Document', new mongoose.Schema({
      name: { type: String },
      description: { type: String },
      subCategory: { type: mongoose.Schema.Types.ObjectId }
}));

const Category = mongoose.model('Category', new mongoose.Schema({
    name: { type: String },
    subCategories: [
      {
        name: { type: String }
      }
    ]
  })
);

var cat1 = await new Category({ name: 'cat1', subCategories: [{ name: 'sub-1-cat-1' }, { name: 'sub-1-cat-2' } ]}).save();
var cat2 = await new Category({ name: 'cat2', subCategories: [{ name: 'sub-2-cat-1' }, { name: 'sub-2-cat-2' } ]}).save();

await new Document({ name: 'doc1', description: 'blabla', subCategory: cat2.subCategories[1] }).save();

const results = Document.find({}).populate('subCategory');

// results[0].subCategory is empty?! why?

1 个答案:

答案 0 :(得分:0)

该子类别必须是猫鼬模型才能被填充,当前您要填充的subCategory只是Category模型的一个数组项,因此我将重构上面发布的代码:

const SubCategory = mongoose.model('SubCategory', new mongoose.Schema({
      name: { type: String }
}));

const Document = mongoose.model('Document', new mongoose.Schema({
      name: { type: String },
      description: { type: String },
      subCategory: { type: mongoose.Schema.Types.ObjectId, ref: "SubCategory" }
}));

const Category = mongoose.model('Category', new mongoose.Schema({
    name: { type: String },
    subCategories: [
      { type: mongoose.Schema.Types.ObjectId, ref: "SubCategory" }
    ]
  })
);

var sub1Cat1 = await new SubCategory({ name: 'sub-1-cat-1' }).save();
var sub1Cat2 = await new SubCategory({ name: 'sub-1-cat-2' }).save();

var sub2Cat1 = await new SubCategory({ name: 'sub-2-cat-1' }).save();
var sub2Cat2 = await new SubCategory({ name: 'sub-2-cat-2' }).save();

var cat1 = await new Category({ name: 'cat1', subCategories: [sub1Cat1, sub1Cat2 ] }).save();
var cat2 = await new Category({ name: 'cat2', subCategories: [sub2Cat1, sub2Cat2 ] }).save();

await new Document({ name: 'doc1', description: 'blabla', subCategory: cat2.subCategories[1] }).save();

const results = Document.find({}).populate('subCategory');

// results[0].subCategory is not empty!