2016-07-08 23 views
1

我正在嘗試使用$ addToSet向流星中的個人檔案集合添加樂器。該代碼在mongo中工作,但不會在流星方法調用中工作。我能夠使用$ set更新所有其他字段而沒有任何問題,所以我知道這是找到了正確的用戶。

updateInstruments(instruments) { 
if (!this.userId) { 
    throw new Meteor.Error('not-logged-in', 
    'Must be logged in to update last name.'); 
} 

check(instruments, String); 

if (instruments.length === 0) { 
    throw Meteor.Error('instruments-required', 'Must provide at least one instrument.'); 
} 

let instrArray = instruments.split(','); 
instrArray.forEach(function(instrument){ 
    instrument = instrument.trim(); 
    Profiles.update({ userId: this.userId }, { $addToSet: { instruments: instrument } }); 
}); 

},

我甚至試過:

Profiles.update({ userId: this.userId }, { $addToSet: { instruments: {$each: [instrument] } }}); 

還有:

Profiles.update({ userId: this.userId }, { $addToSet: { instruments: [instrument] }}); 

我自己也嘗試$推什麼都沒有發生有作爲。流星中是否有某種錯誤?是否有其他設置需要配置以允許更新數組?

UPDATE: 每請求時,這裏的客戶端代碼:

updateInstruments() { 
    if (_.isEmpty(this.data.instruments)) return; 
     var self = this; 
     let instruments = this.data.instruments; 
     this.callMethod('updateInstruments', instruments, (err) => { 
     if (err) return this.handleError(err); 
     }); 
} 

謝謝!

+0

你能否請你也包括你的客戶端代碼?這可能是您如何從客戶端傳遞'樂器'並進行分割,裁剪所導致的問題。 – Luna

回答

1

我想出了這個問題。我忘記了'this'的範圍在inline'instrArray.forEach'函數中發生了變化,導致this.userId'undefined'。個人檔案集合無法找到記錄。我改變了下面的代碼:

let instrArray = instruments.split(','); 
instrArray.forEach(function(instrument){ 
    instrument = instrument.trim(); 
    Profiles.update({ userId: this.userId }, { $addToSet: { instruments: instrument } }); 
}); 

到:

let userId = this.userId; 
let instrArray = instruments.split(','); 
instrArray.forEach(function(instrument){ 
    instrument = instrument.trim(); 
    Profiles.update({ userId: userId }, { $addToSet: { instruments: instrument }  }); 
}); 

感謝大家看在我的代碼!

0

您的查詢對我來說很好。只要你在服務器上這樣做,你就不需要配置任何東西。不是流星中的一個錯誤。