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 = 'new@new.new';
user['username'] = newValue;
user['contacts.$.email'] = newValue;
console.log(user['username']); // logs new@new.new
console.log(user['contacts.$.email']); // logs new@new.new
user.save(...);
No error occurs and username gets successfully updated, while contacts sub-document is still empty. What do i miss there?
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 = 'new@new.new';
user.set('contacts.email', newValue);
user.save(...);
Or you can modify the embedded email
field directly:
var newValue = 'new@new.new';
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}
}
});
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.