【问题标题】:How to use mongoose to add new filed in existed collection如何使用猫鼬在现有集合中添加新字段
【发布时间】:2022-10-24 06:35:30
【问题描述】:

我搜索猫鼬方法将我的新字段添加到现有集合中,我尝试了 findByIdAndUpdate() 的功能,但它不起作用,还有其他方法吗?请告诉我!

这是我的架构代码:

const mongoose=require('mongoose');
const Schema=mongoose.Schema;

const AccountSchema=new Schema({
    account:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    },
    strick:false
    

});

const Account=mongoose.model('Account',AccountSchema);

module.exports=Account;

和应用代码:

  app.post('/api/sendToShoppingCart',async(req,res)=>{
        const db=await mongoose.connect("private");
        const instance=await Account.findByIdAndUpdate(req.body.memberID,{
            shoppingCart:Array //new field
        });
        console.log(instance);//it find it
        await instance.save(); //save update

        db.disconnect();//clsoe mongodb
    });

谢谢你的帮助!

【问题讨论】:

  • 当前代码有什么问题?
  • @KonradLinkowski,我的 Mongodb 云没有增加新的字段,我不知道为什么它不能工作!
  • 为什么要传递数组构造函数而不是数组[]

标签: node.js mongodb mongoose


【解决方案1】:

首先,您需要在架构中定义 shoppingCart 以便它可以反映您的更改

const AccountSchema = new Schema({
  account: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  strick: false,
  shoppingCart: {
    type: [
        {
          type: Schema.Types.Mixed
        }
      ],
      default: [],
  },
});

【讨论】:

    猜你喜欢
    • 2014-08-22
    • 2018-08-26
    • 2021-08-05
    • 2018-11-28
    • 2017-11-27
    • 2021-11-25
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多