【问题标题】:I am trying to create a new Cart schema with a request我正在尝试使用请求创建新的购物车模式
【发布时间】:2019-12-09 13:22:39
【问题描述】:

我的数据没有正确保存

这是我的架构

  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)
};

这是我的发帖请求

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;

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

这是我要发送到服务器的内容

[{

"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
}

【问题讨论】:

    标签: mongodb mongoose schema mern


    【解决方案1】:

    不得不重组这个文件

     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;
    

    【讨论】:

      【解决方案2】:

      你不需要

      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()
      

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

      【讨论】:

      • 好的,我明白了。但是我有两个以上的对象这仍然有效吗?
      • 我应该改变我的架构吗?
      • 是的,您可以将许多产品添加到阵列中,并且具有相同的架构。不需要 ProductModel。
      • 别忘了删除:await newProduct.save();以及所有与新产品相关的
      • 好的,我会试试这个,让你知道结果如何,非常感谢
      【解决方案3】:

      猫鼬模式没有构造函数

      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();
      

      【讨论】:

      • 好的,我将问题更新为我当前的代码。它有效,但仅当我发送单个对象时。当我发送一个带有嵌套对象的数组时它不起作用我的数据是以这种方式构造的
      • const purchase = await newPurchase.save() + products;这是什么意思?
      • 事件最好只是给出一个你想要的响应示例以及来自哪里?
      • 这是我的代码中的一个错字,现在我只是调用 purchase = newPurchase 我在床上,我将在早上更新。
      • 我不明白你为什么要连接模型。 purchase = newPurchase + products;如果您想购买信息,请执行res.json(newPurchase.toJSON());
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 2020-10-19
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多