Eugene Kostrikov
Eugene Kostrikov

Reputation: 7119

Mongoose, update sub-document

Consider the following schema

Var Schema = new Schema({
  username: {Type: String},
  ...
  ...
  contacts: {
    email: {Type: String},
    skype: {Type: String}
    }
  })

As every user can state only one email and skype i don't want to use array with contacts.

Discarding DB queries and error handling i try to do something like

// var user is the user document found by id
var newValue = '[email protected]';
user['username'] = newValue;
user['contacts.$.email'] = newValue;
console.log(user['username']); // logs [email protected]    
console.log(user['contacts.$.email']); // logs [email protected]
user.save(...);

No error occurs and username gets successfully updated, while contacts sub-document is still empty. What do i miss there?

Upvotes: 2

Views: 4601

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

Remove the $ index from your path as contacts isn't an array, and use the set method instead of trying to directly manipulate the properties of user using a path:

var newValue = '[email protected]';
user.set('contacts.email', newValue);
user.save(...);

Or you can modify the embedded email field directly:

var newValue = '[email protected]';
user.contacts.email = newValue;
user.save(...);

If it's not just a typo in your question, your other problem is that you need to use type and not Type in your schema definition. So it should be:

var Schema = new Schema({
  username: {type: String},
  ...
  ...
  contacts: {
    email: {type: String},
    skype: {type: String}
    }
  });

Upvotes: 7

Related Questions