【问题标题】:Undestanding mongoose了解猫鼬
【发布时间】:2020-10-29 21:46:09
【问题描述】:

早上好, 我在用户对象中创建购物车字段时遇到问题,更准确地说,我定义了一个简单的模型

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({

name:{
    type:String,
    required: true
},

cart:[

    {qty:{type:Number,required:true}},
    {product:{type:String,required:true}}
    ]
   });

   module.exports= mongoose.model('user',userSchema);

当我尝试使用上面的模型在数据库中插入数据时出现意外行为: 如果我使用以下代码将数据发送到数据库:

    const cart  = {product:'lamp', qty:4};

    const utente = new User({
    name:'mario',
    cart:cart
    
    });
    
    
    utente.save()
    

会这样保存:

_id:5f06e8140a3290711bb7681f 名称:“马里奥” 购物车:数组 0:对象 _id:5f06e8140a3290711bb76820 数量:4 __v:0

如您所见,而不是获取应该包含带有“灯”的产品密钥的购物车数组 value 和一个值为 4 的 qty 键,我得到一个包含 _ID 和 qty 的数组,这是为什么呢?

【问题讨论】:

    标签: node.js arrays object mongoose


    【解决方案1】:

    架构定义存在问题。目前,您已经在购物车数组中定义了两个 JSON 对象。请尝试如下更新架构以获得问题中提到的预期结果

    const userSchema = new mongoose.Schema({
      name: {
        type: String,
        required: true,
      },
    
      cart: [
        {
          qty: { type: Number, required: true },
          product: { type: String, required: true },
        },
      ],
    });
    

    【讨论】:

      猜你喜欢
      • 2013-05-08
      • 2021-05-03
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2016-04-28
      • 2021-11-25
      相关资源
      最近更新 更多