首页 > 解决方案 > 为什么填充在 mongodb 中返回空结果

问题描述

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

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.jsmongodbmongoose

解决方案


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

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!

推荐阅读