【问题标题】:Mongoose, update sub-documentMongoose,更新子文档
【发布时间】:2013-11-01 20:36:03
【问题描述】:

考虑以下架构

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

没有错误发生并且用户名被成功更新,而联系人子文档仍然是空的。 我在那里想念什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    从路径中删除$ 索引,因为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}
        }
      });
    

    【讨论】:

    • 谢谢,user.set(key, newValue) 对我有用。但是请注意,用 user.contacts.email = newValue 直接修改是没有效果的。
    • 那么您的架构定义有问题。请参阅我的更新答案。
    • 是的,我的架构与您的完全一样,类型定义为小写“t”。当然,原始问题中有错别字。无论如何,user.set() 运行良好,在我的情况下甚至更好,因为它需要更少的代码。
    • +1 set 方法帮助我将新字段保存到仅在我的用户模式中定义为对象的子文档中。 user.email = newValue 保存得很好,因为它在我的架构中进行了描述,但 user.mobileDevice.phoneNumber = newValue 不会保存。我不得不使用 set 方法:user.set('mobileDevice.phoneNumber', newValue) 来让数据持久化到数据库中。
    猜你喜欢
    • 1970-01-01
    • 2017-03-17
    • 2021-12-23
    • 2015-07-12
    • 2014-11-27
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多