猫鼬,更新子文档

尤金·科斯特里科夫(Eugene Kostrikov)

考虑以下架构

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

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

香港强尼

$从您的路径contacts(不是数组)中删除索引,并使用set方法而不是尝试直接操纵user使用路径的属性

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

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

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

如果您的问题不仅仅是错别字,那么您的另一个问题就是您需要使用type而不是Type在模式定义中。因此应该是:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章