Mongoose,更新子文档

时间:2013-10-31 14:10:07

标签: node.js mongodb mongoose

考虑以下架构

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

当联系人子文档仍为空时,不会发生错误并且用户名成功更新。 我在那里想念什么?

1 个答案:

答案 0 :(得分:5)

从您的路径中删除$索引,因为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}
    }
  });
相关问题