【问题标题】:Insert online shopping cart items into MongoDB using Mongoose使用 Mongoose 将在线购物车项目插入 MongoDB
【发布时间】:2020-04-05 05:44:15
【问题描述】:

我正在尝试使用 mongoose 模式将一篮商品作为 JSON 对象插入到 MongoDB 集合中。

正在存储客户的 ID(来自用户数据库),但 购物车商品没有。这是我的代码:

包含在名为cartData: { data:[] }的局部变量app.js中的示例订单数据:

{
    data: [
      item {
        name: "Product Name 1",
        price: '2.99',
        sku: '13579',
        count: 8
      },
      item {
        name: 'Product Name 2',
        price: '21.99',
        sku: '24680',
        count: 2
      }
    ]
}

Cart.js(购物车架构):

const mongoose = require("mongoose")

const CartSchema = new mongoose.Schema({
    customerID: {
        type: String,
        required: true
    },
    cartContents: {
        type: [Object]
    },
    date: {
        type: Date,
        default: Date.now
    }
}, { collection: "ordersDB" })

const Cart = mongoose.model('Cart', CartSchema)
module.exports = Cart

app.js(订单提交代码):

const Cart = require("../models/Cart")
const customerID = req.user.customerID //Acquired from user database

const newOrder = new Cart({
    customerID,
    cartData
})
newOrder.save()
    .then(customer => {
        req.flash("successful", "Your order has been submitted!")
        res.redirect("/somepage")
    })
    .catch(err => console.log(err))

结果:

_id: abcd1234
> cart: Object
    > type: Array
        > <The Infinite Abyss Of Nothingness aka Empty>
customerID: "1234567890"
date: 2019-12-11T21:14:40.825+00:00
__v: 0

任何对此问题的见解将不胜感激。

【问题讨论】:

    标签: javascript node.js json mongodb mongoose


    【解决方案1】:

    根据提供的模式,Mongoose 期望您传递一个名为 cartContents 的字段。与您的架构不兼容的任何其他字段都将被忽略。要解决这个问题,只需明确命名您的字段:

    const newOrder = new Cart({
        customerID,
        cartContents: cartData
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多