如何使用mongoosejs在mongoDB中存储嵌套数据?

问题描述 投票:0回答:0

我想存储在 mongodb 中的示例数据。 使用邮递员检查 API.

{
  "id": "242kd",
  "user_id": "123gsgshsghgshgs6",
  "product_id_quantity": [
    {
      "product_id": 8,
      "quantity": 2
    },
    {
      "product_id": 7,
      "quantity": 5
    }
  ]
}

控制器代码:cartController.js

  exports.createCart = (req, res, next) => {
  const productIdQuantity = new productIdQuantitySchema({
    product_id: req.body.product_id_quantity.product_id,
    quantity: req.body.product_id_quantity.quantity,
  })
  const cart = new Cart({
    userId: req.body.user_id,
    product_id_quantity: [productIdQuantity],
  });
  cart.save().then(result => {
    res.status(201).json({
      message: "Cart Created!",
      result: result
    });
  })
  .catch(err => {
    res.status(500).json({
      message: err+"Error occuer at the time of cart creation!"
    });
  });
}

模型代码:cartModel.js

const productIdQuantitySchema = mongoose.Schema({
  id: String,
  product_id: { type: String, required: true },
  quantity: { type: Number, required: true },
});

const cartSchema = mongoose.Schema({
  id: String,
  userId: { type: String, required: true },
  product_id_quantity: productIdQuantitySchema,
});

邮递员出错

{
    "message": "ValidationError: product_id_quantity: Cast to Embedded failed for value \"[ { _id: new ObjectId(\"643c330dd33750a122282f3f\") } ]\" (type Array) at path \"product_id_quantity\" because of \"ObjectExpectedError\"Error occuer at the time of cart creation!"
}

邮差截图:

你能帮我在代码(控制器/模型)或邮递员身上或其他任何地方需要改变什么吗?

node.js mongodb mongoose mongoose-schema
© www.soinside.com 2019 - 2024. All rights reserved.