我正在尝试使用请求创建一个新的购物车模式

I am trying to create a new Cart schema with a request

我的数据没有被正确保存

这是我的架构

  const mongoose = require('mongoose');

const ProductSchema = mongoose.Schema({
  colorC: String,
  sizeC: String,
  date: Date,
  title: String,
  transactionID: Number,
  count: Number
});

const CartSchema = mongoose.Schema({
  products: [ProductSchema]
});

const Cart = mongoose.model('Cart', CartSchema);

module.exports = {
  cartModel: mongoose.model('Cart', CartSchema),
  productModel: mongoose.model('Product', ProductSchema)
};

这是我的post请求

const express = require('express');
const Cart = require('../models/Cart');
const models = require('../models/Cart');
const router = express.Router();

router.post('/', async (req, res) => {
  const { colorC, sizeC, date, title, transactionID, count } = req.body;
  try {
    const newPurchase = new models.cartModel({
      products: [
        {
          title,
          colorC,
          sizeC,
          count,
          date,
          transactionID
        }
      ]
    });

    const purchase = await newPurchase.save();

    res.json(purchase);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

module.exports = router;

当我将数据作为包含两个对象的数组发送时 none 例如,数据显示应该显示我输入的对象。 当我发送这个时,服务器不会在数组中保存任何产品。

这是我发送给服务器的内容

[{

"colorC": null,
"count": 1,
"date": "Mon Jul 29 2019 02:08:07 GMT-0400 (Eastern Daylight Time)",
"sizeC": "Small",
"title": "COMME DES GARCONS TEE",
"transactionID": 1564380487732

},{

"colorC": null,
"count": 1,
"date": "Mon Jul 29 2019 02:08:07 GMT-0400 (Eastern Daylight Time)",
"sizeC": "Small",
"title": "COMME DES GARCONS TEE",
"transactionID": 1564380487732

}]

这是保存在数据库中的数据

{
    "_id":{"$oid":"5d42ab9f4ec81021f0136e95"},
    "products":[{"_id":{"$oid":"5d42ab9f4ec81021f0136e94"}}]
    ,"__v":{"$numberInt":"0"}
    }

我希望数据看起来像这样

{
    "_id": "5d439bc758a1f004b876bac3",
    "products": [
        {
            "_id": "5d439bc758a1f004b876bac4",
            "title": "COMME DES GARCONS TEE",
            "colorC": null,
            "sizeC": "Small",
            "count": 1,
            "date": "2019-07-29T06:08:07.000Z",
            "transactionID": 1564380487732
        }
    ],
    "__v": 0
}

猫鼬模式没有构造函数

new models.ProductSchema({ ...data })

会给你一个错误。

为此,您必须导出模式的模型

module.exports =  { 
    cartModel: mongoose.model('Cart', CartSchema), 
    productModel: mongoose.model('Cart', ProductSchema),
}

现在您可以使用模型构造函数来实现您想要的

const newProduct = new models.cartModel({
      colorC,
      sizeC,
      date,
      title,
      transactionID,
      count
    })

然后您可以使用您的产品存储到任何您想要的地方

 const newPurchase = new models.CartSchema({
      products: [newProduct.toJSON()]
    });

是的,你必须同时保存两者。

newProduct.save();
newPurchase.save();

你不需要

productModel: mongoose.model('Product', ProductSchema)

您可以只保存完整的购物车 json:

const newPurchase = new models.cartModel({
    products:[{ 
        "colorC": null,
        "count": 1,
        "date": "Mon Jul 29 2019 02:08:07 GMT-0400 (Eastern Daylight Time)",
        "sizeC": "Small",
        "title": "COMME DES GARCONS TEE",
        "transactionID": 1564380487732
    },{
        "colorC": null,
        "count": 1,
        "date": "Mon Jul 29 2019 02:08:07 GMT-0400 (Eastern Daylight Time)",
        "sizeC": "Small",
        "title": "COMME DES GARCONS TEE",
        "transactionID": 1564380487732
    }]
});

await newPurchase.save()

(显然你必须从请求正文中动态获取值)

不得不重组这个文件

 const express = require("express");
    const models = require("../models/Cart");
    const router = express.Router();

    router.post("/", (req, res) => {
      const newPurchase = new models.cartModel({
        products: req.body.map(element => {
          const { colorC, sizeC, date, title, transactionID, count } = element;
          return { colorC, sizeC, date, title, transactionID, count };
        })
      });

      newPurchase
        .save()
        .then(purchase => res.json(purchase))
        .catch(err => {
          console.error(err.message);
          res.status(500).send("Server Error");
        });
    });

    module.exports = router;