node.js - Mongoose: assign field of type 'array of Strings' -
I am using an array of stars to save emails:
var user = New schema ({// other field ... email: [string]});
Saying that this area may have trouble updating, Email 1 and Email 2 are values I get from viewing:
It works well:
user.emails = [email1, email2]; User.save (); // fields are updated, all good
and this is not the like:
user.emails [0] = email1; User.emails [1] = Email2; User.save (function (err, savedUser) {console.log (savedUser.emails); // Updated array [email1, email2] // But if I now get the user, then over the changes in the 'Email' field Will not done });
But, oddly, it works:
user.emails = [email1]; User.emails [1] = Email2; User.save (); // user.emails == [email1, email2]; Can anyone explain why this is happening? It is not well documented, That you are triggering to detect Mongoose's field change so that it knows that the array has been modified and saved.
Directly an array element has not been modified in its square bracket through its index so that you must flag it manually:
user.emails [0] = email1; User.markModified ('email');
Or you can do it at once, using the method of the Mongoos array:
User email .set (0, email 1);
Overwriting the entire array field also triggers why this works for you:
user.emails = [email1, email2];
Also:
user.emails = [email1]; User.emails [1] = Email2;
Which also means:
user.emails = []; User.emails [0] = Email 1; User.emails [1] = Email2;
Comments
Post a Comment