【问题标题】:Why populate returns empty results in mongodb为什么填充在 mongodb 中返回空结果
【发布时间】:2019-05-04 17:42:28
【问题描述】:

我想填充我的属性(子类别),但它返回空,尽管我的数据库中有结果。我错过了什么吗?我按照猫鼬中的填充方法:

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?

【问题讨论】:

  • 子类别必须是猫鼬模型才能被填充,目前您要填充的子类别只是类别模型的数组项
  • 还能做吗?也许不使用填充?还是使用另一种语法填充?

标签: node.js mongodb mongoose


【解决方案1】:

子类别必须是猫鼬模型才能被填充,目前您尝试填充的子类别只是类别模型的数组项,因此我会将您在上面发布的代码重构为:

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!

【讨论】:

  • 我确实希望 Category 和 SubCategory 在同一个集合中。为什么做不到?
  • @JonSud 您可以按照我上面提到的方式使用它,也可以不尝试使用子类别填充 Document 模型,而是将对象放入其中。您不能按照上面的方式进行操作,因为 mongoose 使用该字段中指定的 ObjectId 和 ref 属性填充字段(需要 ref 属性,因此 mongoose 知道要为文档获取哪个集合指定的 ObjectIds)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2015-08-26
  • 2011-01-12
相关资源
最近更新 更多