繁体   English   中英

猫鼬,更新子文档

[英]Mongoose, update sub-document

考虑以下架构

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

由于每个用户只能声明一封电子邮件和Skype,因此我不想将数组用于联系人。

放弃数据库查询和错误处理,我尝试做类似的事情

// 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(...);

没有任何错误,并且用户名已成功更新,而联系人子文档仍然为空。 我在那里想念什么?

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

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

或者,您可以直接修改嵌入式email字段:

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

如果您的问题不只是拼写错误,那么另一个问题是您需要在模式定义中使用type而不是Type 因此应该是:

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