简体   繁体   English

猫鼬,更新子文档

[英]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. 由于每个用户只能声明一封电子邮件和Skype,因此我不想将数组用于联系人。

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: 因为contacts不是数组,所以从路径中删除$索引,并使用set方法而不是尝试直接使用路径来操纵user的属性:

var newValue = 'new@new.new';
user.set('contacts.email', newValue);
user.save(...);

Or you can modify the embedded email field directly: 或者,您可以直接修改嵌入式email字段:

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. 如果您的问题不只是拼写错误,那么另一个问题是您需要在模式定义中使用type而不是Type So it should be: 因此应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM