我有2个要链接的猫鼬模型。创建车辆的“父”模式和创建费用的“子”模式。在我的父架构上,我有一个“ expenses”属性(设置为数组),每次从前端提交费用时,我都希望使用众多的“费用”子模式来填充。
const vehicleSchema = mongoose.Schema({
name: {
type: String
},
registration: {
type: String
},
make: {
type: String
},
model: {
type: String
},
mileage: {
type: Number
},
user: {
type: String
},
expenses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "ExpensesModel"
}
]
});
const expensesSchema = mongoose.Schema({
name: {
type: String
},
value: {
type: Number
},
description: {
type: String
},
date: {
type: Date,
default: Date.now()
},
vehicle: {
type: mongoose.Schema.Types.ObjectId,
ref: "VehicleModel"
}
});
const VehicleModel = mongoose.model("VehicleModel", vehicleSchema);
const ExpensesModel = mongoose.model("ExpensesModel", expensesSchema);
然后将它们导出到我的后端路由文件中以处理表单提交。
router.post("/:id", auth, async (req, res) => {
VehicleModel.findOne({
_id: req.params.id
})
.populate("expenses")
.exec((err, product) => {
if (err) {
return console.log(err);
}
return console.log(product);
});
});
我一直让结果返回“ null”。我能理解,因为路由中的代码显然不完整。我只是不知道如何完成它。我已经做了很多尝试,只是在上面提交了一个基本尝试。
谁能建议它应该如何工作?我认为错误在于填充字段,因为它没有在任何地方引用费用模型?