猫鼬填充 returns [对象] 而不是结果

Mongoose Populate returns [Object] instead of result

我对 Mongoose 的 Population 方法有疑问。按照下面的结构

const CompanySchema = new Schema({
  name: String,
  logo: String,
  description: String,
  address: String,
  website: String,
  phone: String,
  email: String,
  warehouses: [{ type: Schema.Types.ObjectId, ref: 'CompanyWarehouses' }],
});

const CompanyWarehouses = new Schema({
  company: { type: Schema.Types.ObjectId, ref: 'Company' },
  city: String,
});

我在两个表中都有一些条目。我正在尝试使用 Mongoose 中的 Population 来填充每个公司的 warehouses 字段。

使用以下查询

Company.find({}, 'warehouses -_id')
  .populate({
    path: 'warehouses',
  })
  .exec((err, docs) => {
     console.log(docs);
  }); 

我得到以下结果

[ { warehouses: [ [Object], [Object], [Object] ] },
  { warehouses: [ [Object], [Object] ] },
  { warehouses: [ [Object], [Object] ] },
  { warehouses: [ [Object] ] },
  { warehouses: [] },
  { warehouses: [ [Object] ] } ]

如果我在没有填充的情况下这样做,我会得到仓库的 ID

[ { warehouses: 
     [ 5c2765e86351ec4f1e219d6b,
       5c2765e86351ec4f1e219d6c,
       5c2765e86351ec4f1e219d6d ] },
  { warehouses: [ 5c2773596351ec4f1e219d77, 5c2773596351ec4f1e219d78 ] },
  { warehouses: [ 5c277c766351ec4f1e219d82, 5c277c766351ec4f1e219d83 ] },
  { warehouses: [ 5c27843c6351ec4f1e219d90 ] },
  { warehouses: [] },
  { warehouses: [ 5c279b8ecebdea072f0bacd5 ] } ]

如果我查询 CompanyWarehousespopulate company 文件,我得到的人口是正确的

CompanyWarehouses.find()
    .populate('company')
    .exec((err, docs) => {
      console.log(docs);
    });

[ { _id: 5c279b8ecebdea072f0bacd5,
    company: 
     { warehouses: [Array],
       _id: 5c279b3acebdea072f0baccc,
       name: 'sadsa',
       phone: '2323',
       email: 'sss@ss.ss',
       city: 'dsadsadsa',
       address: 'sadadsa',
       logo: 'logo.png' },
    city: 'ssdsa',
    __v: 0 }]

谁能解释一下我在这里遗漏了什么

LE:

我已经这样定义了两个模型

module.exports = mongoose.model('Company', CompanySchema);
module.exports = mongoose.model('CompanyWarehouses', CompanyWarehouses);

我觉得问题出在这里

warehouses: [{ type: Schema.Types.ObjectId, ref: 'CompanyWarehouses' }]

您正在将价值 CompanyWarehouses 赋予 ref

尝试创建两个 Schema Constant 的实例,然后将该实例变量分配给 ref

    const CompanySchema = new Schema({
      ...,
      warehouses: [{ type: Schema.Types.ObjectId, ref: 'companywarehouses' }],
    });

    const CompanyWarehouses = new Schema({
      company: { type: Schema.Types.ObjectId, ref: 'company' },
      ...
    });


   // instance of both Model
    const CompanySch = mongoose.model('company', CompanySchema);
    const WareHousesSch = mongoose.model('companywarehouses', CompanyWarehouses);

这是由于 console.log() 限制了它将显示的数据的深度。

如果您想查看docs的完整内容,您可以将其记录为JSON:

console.log('%j', docs);

或移除深度限制:

const { inspect } = require('util');

...

console.log( inspect(docs, { depth : null }) );