【发布时间】:2020-05-18 17:32:46
【问题描述】:
我刚刚开始使用 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
})
然后我想用 Car Model(他们的品牌)的数据填充汽车数组。然而,运行下面的填充只返回一个文档 [{"_id":"....","brand":"Toyota","__v":0}]。数组长度为 1,但如果我检查数据库或跳过填充调用,显然会存储很多汽车 ID。
Owner.findById(ownerId).populate('cars').exec(function (err, owner) {
if (err) console.log(err)
console.log(owner) //this only returns one object
})
我做错了什么?如您所知,我有点困惑,不胜感激。谢谢!
【问题讨论】:
标签: javascript mongoose model associations populate