[英]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.