[英]Relationship mongoose
我有兩個模式,其中一個依賴於另一個來保存。
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)
}
})
我經常使用
idproduct: {
type: moongose.Schema.ObjectId,
required: true
},
這樣郵件就可以正常工作了
大聲笑,我發現了錯誤:
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()
})
呵呵呵,對不起伙計們......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.