Node.js:无法读取未定义的属性“ productId”

时间:2020-06-25 08:31:02

标签: node.js

我只是想用node.js进行关系操作。

订购模式:

const mongoose = require("mongoose");

const orderSchema = mongoose.Schema({
    product: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product',
        required: true
    },
    quantity: {
        type: Number,
        default: 1
    }
});

module.exports = mongoose.model("Order", orderSchema);

产品架构:

const mongoose = require("mongoose");

const productSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    date: {
        type: Date,
        defaılt: Date.now
    }
});

module.exports = mongoose.model('Product', productSchema);

路线:

router.post("/", (req, res) => {
    console.log(req.body);
    const order = new Order({
        quantity: req.body.quantity,
        product: res.body.productId
    });
    

});

输出:

{productId:'5ef31d158399ee48139f330f'} TypeError:无法读取未定义的属性“ productId”

2 个答案:

答案 0 :(得分:1)

router.post("/", (req, res) => {
    console.log(req.body);
    const order = new Order({
        quantity: req.body.quantity,
        product: req.body.productId
    });
    

});

它的req.body.productId不是res.body.productId。

答案 1 :(得分:1)

您的代码有问题

res.body.productId更改为req.body.productId

router.post("/", (req, res) => {
 console.log(req.body);
 const order = new Order({
     quantity: req.body.quantity,
     //you use response instead of request
     product: res.body.productId
 });
});