Mongoose: assign a field like "array of strings"

I use an array of strings to save emails:

var user = new Schema({
  // other fields...

  emails: [String]
});

You have problems updating this field. Let's say email1 and email2 are the values ​​that I get from the view:
This works well:

user.emails = [email1, email2];
user.save();
// fields are updated, all good

And this is not so:

user.emails[0] = email1;
user.emails[1] = email2;
user.save(function(err, savedUser) {
  console.log(savedUser.emails); // updated array [email1, email2]
  // but if I retrieve now the user, the 'emails' field will not have above changes.
});

But, oddly enough, this works:

user.emails = [email1];
user.emails[1] = email2;
user.save();
// user.emails == [email1, email2];

Can someone explain why this is happening?

+4
source share
1 answer

This is not well documented, but when manipulating the fields of an array, you need to make sure that you run change detection in Mongoose so that it knows that the array has been changed and needs to be saved.

, , markModified

user.emails[0] = email1;
user.markModified('emails');

, set Mongoose:

user.emails.set(0, email1);

, :

user.emails = [email1, email2];

:

user.emails = [email1];
user.emails[1] = email2;

, :

user.emails = [];
user.emails[0] = email1;
user.emails[1] = email2;
+10

All Articles