How does Mongo update the document without removing the other fields?



  • There's a pattern:

    var userSchema = new Schema({
    field: {},
    field2: {},
    field3: {
        innerField1: String,
        innerField2: String,
        innerField3: String,
        innerField4: String,
        innerField5: String,
        innerField6: String
    }
    });
    

    Let's assume the scheme is complete and I need to update some data.

    Example of request: (I don't know which field field I'm going to be here, can be completely different all the time)

    {
       field3: {
          innerField2: String,
          innerField4: String
       }
    }
    

    How am I supposed to update the sample field in the Field3 and not remove the rest?

     Schema.findOneAndUpdate({_id: userId}, {$set: req.body.field3}, function(err, res) {});
    

    It doesn't work, removes the other fields:

    I'm waiting for your answers, thank you!



  • Schema.UpdateById(userId, {$set:{"field3": req.body.field3}}, function(err, res) {});
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2