首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关系mongoose

关系mongoose
EN

Stack Overflow用户
提问于 2019-04-12 03:26:42
回答 2查看 30关注 0票数 0

我有两个模式,其中一个依赖于另一个来保存。

代码语言:javascript
复制
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)

另一种是:

代码语言:javascript
复制
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)

但当我尝试保存一个订单时,数据库中已存在一个产品:

代码语言:javascript
复制
{
    "product":"5cae6ff5d478882ed8725911",
    "quantity":3
}

显示错误:错误: ReferenceError:未定义产品

这是我用来保存新订单的控制器:

代码语言:javascript
复制
router.post('/register', async (req, res) => {
    try {
        const order = await Order.create(req.body)

        return res.send({ order })
    }
    catch (error) {
        console.error('Error:', error)
    }
})
EN

回答 2

Stack Overflow用户

发布于 2019-04-12 03:59:13

我通常用

代码语言:javascript
复制
    idproduct: {
         type: moongose.Schema.ObjectId,
         required: true
     },

这样,文章就可以正常工作了

票数 0
EN

Stack Overflow用户

发布于 2019-04-12 05:05:26

哈哈,我发现了错误:

代码语言:javascript
复制
OrderSchema.pre('save', async function(next) {
    this.total_price = product.price * quantity

    next()
})

我忘了用'THIS',对吗?

代码语言:javascript
复制
OrderSchema.pre('save', async function(next) {
    this.total_price = this.product.price * this.quantity

    next()
})

哈哈哈,对不起伙计们。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55639830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档