我有两个模式,其中一个依赖于另一个来保存。
const OrderSchema = new moongose.Schema({
product: {
type: moongose.Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true,
default: 1,
},
total_price: {
type: Number,
}
})
OrderSchema.pre('save', async function(next) {
this.total_price = product.price * quantity
next()
})
const Order = moongose.model('Order', OrderSchema)另一种是:
const ProductSchema = new moongose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String
},
photo: {
data: Buffer,
contentType: String
}
})
const Product = moongose.model('Product', ProductSchema)但当我尝试保存一个订单时,数据库中已存在一个产品:
{
"product":"5cae6ff5d478882ed8725911",
"quantity":3
}显示错误:错误: ReferenceError:未定义产品
这是我用来保存新订单的控制器:
router.post('/register', async (req, res) => {
try {
const order = await Order.create(req.body)
return res.send({ order })
}
catch (error) {
console.error('Error:', error)
}
})发布于 2019-04-12 03:59:13
我通常用
idproduct: {
type: moongose.Schema.ObjectId,
required: true
},这样,文章就可以正常工作了
发布于 2019-04-12 05:05:26
哈哈,我发现了错误:
OrderSchema.pre('save', async function(next) {
this.total_price = product.price * quantity
next()
})我忘了用'THIS',对吗?
OrderSchema.pre('save', async function(next) {
this.total_price = this.product.price * this.quantity
next()
})哈哈哈,对不起伙计们。
https://stackoverflow.com/questions/55639830
复制相似问题