Home > Blockchain >  How to use mongoose to add new filed in existed collection
How to use mongoose to add new filed in existed collection

Time:10-25

I search for the mongoose method to add my new field into existed collection,I try the function of findByIdAndUpdate(),but it doesnt work ,are there another method?Please,tell me!

this is my schema code:

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;

and application code:

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

Thanks for your help!

CodePudding user response:

first you need to define shoppingCart within your schema so it can reflect your changes

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