简体   繁体   中英

Mongoose update the field of the nested document not working

I've tried to update the field of the nested sub document using mongoose.
Here are the model and source code.
Model

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var info_schema = mongoose.schema({
   info:Schema.Types.Mixed,
},{collection:'info'});
var InfoModel = mongoose.model('info', info_schema);

I've tried to execute db.info.updateMany({'info.addition.group':myid},{$set:{'info.addition.field1':'a','info.addition.field2':'b'}}) in mongoshell.
It worked well,but it didn't work using mongoose.

 InfoModel.updateMany({'info.addition.group':myid},{$set:{'info.addition.field1':'a','info.addition.field2':'b'}}).exec();    

Why doesn't mongoose update the field of the sub nested document?
So I tried to described the model in more detail.

 var info_schema = mongoose.schema({
   info:{
      addition:Schema.Types.Mixed,
      otherinfo:String,
      modified:Number,
      ....
    },
 },{collection:'info'});

At this time , mongoose threw out the error.

CastError: Cast to number failed for value "a" at path "addition"

What did I do incorrectly?
What is the reason of this?

This works using your code and modifying it a little bit:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var info_schema = new Schema({  // <-- just use Schema
   info: Schema.Types.Mixed
},{collection:'info'});
var InfoModel = mongoose.model('info', info_schema);

InfoModel.updateMany({'info.addition.group': 1},  // <-- I used 1 for testing
{ $set: { 'info.addition.field1' : 'a', 'info.addition.field2' : 'b' } }).exec()

Tested locally after first creating a record with info.addition.id == 1 so that I can update it etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM