簡體   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