猫鼬Populate()不填充ObjectIds的数组

时间:2020-02-02 22:17:03

标签: javascript mongoose model associations populate

我刚开始使用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
}))

这个想法是,所有者应该能够拥有多辆汽车。因此,我在所有者的cars数组中存储了每辆汽车的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
})

然后,我想用Car Model(其品牌)的数据填充cars数组。但是,运行下面的填充仅返回一个文档[{“ _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 
})

我在做什么错?如您所知,我有些困惑,不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

最初,我在理解为什么无法访问“汽车”数组/为什么总是返回定义时遇到了一些困难,但是后来我意识到,多亏https://stackoverflow.com/a/25004168/2768479中的内森·罗曼诺,这是因为汽车“是嵌套了两个以上级别,因此默认情况下,输出由“ [Object”]表示。只需运行

owner[0].cars

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

相关问题