Mongoose Populate() 不填充 ObjectIds 数组

Mongoose Populate() not populating array of ObjectIds

我刚刚开始使用 Mongoose,我正在尝试使用一个非常基本的示例让 populate() 工作。目前我有两个模型,一个汽车模型和一个所有者模型。

所有者

const mongoose = require('mongoose')

module.exports = mongoose.model('Owner', mongoose.Schema({
  name: String,
  cars: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Car' }]
}))

汽车

const mongoose = require('mongoose')

module.exports = mongoose.model('Car', mongoose.Schema({
  brand: String
}))

这个想法是车主应该能够拥有多辆汽车。因此,我为车主的汽车数组中的每辆汽车存储了一个 ObjectId 引用。

Owner.findById(ownerId, function (err, owner) {
  if (err) console.log(err)

  const c = new Car({ brand: 'Toyota' })

  owner.cars.push(c)
  owner.save()
  console.log(owner.cars) // prints out an array containing multiple car _ids, everything working so far
})

然后我想用汽车模型(他们的品牌)的数据填充汽车数组。 运行 下面只填充 returns 一个文档 [{"_id":"....","brand":"Toyota","__v": 0}]。数组长度为 1,但如果我检查数据库或跳过填充调用,显然存储了很多 Car id。

Owner.findById(ownerId).populate('cars').exec(function (err, owner) {
  if (err) console.log(err)
  console.log(owner) //this only returns one object 
})

我做错了什么?如您所知,我有点困惑,希望得到任何帮助。谢谢!

第一个问题可能与 ObjectId 错误有关。因此,我从 MongoDB 中删除了所有内容并重新开始(我没有更改架构中的任何内容,因此问题不在于此)。在数据库为空的情况下,我创建了一个新的所有者,并将两个汽车 ID 推送到 "cars" 数组。然后我 运行 populate() 再次返回

[
  {
    cars: [ [Object], [Object] ],
    _id: 5e375dc926cd72641cd60d74,
    name: 'James',
    __v: 0
  }
]

最初我很难理解为什么我无法访问 "cars" array/why 它总是返回已定义,但后来我意识到,感谢 中的 Nathan Romano是因为汽车 "are nested more than 2 levels, so by default the output is represented by "[Object"]。只需按 运行

owner[0].cars

我得到了我要找的车,populate() 正在按预期工作。