2016-08-02 97 views
0

這個Meteor服務器代碼試圖在循環中每次插入一個不同的文檔,如果它不存在使用upsert,它只插入第一個文檔,但不插入以下內容,即使它們不同。我究竟做錯了什麼?由於插入文件如果沒有找到

MyCol = new Mongo.Collection('myCol'); 

MyCol.before.insert(function(userId, doc) { 
    doc.userId = userId; 
    doc.createdAt = Date.now(); 
}); 

//the following is inside a loop where C and date changes 
MyCol.upsert({ 
    userId: userId 
}, { 
    $set: { 
    a: 'A', 
    b: 'B', 
    c: C, 
    date: date 
    } 
}); 

回答

0

您需要擴大您的查詢參數爲您upsert

MyCol.upsert({ userId: userId },{ $set: ... }); 

你只需要在查詢一個參數:userId。由於cdate正在改變,你需要將它們包含在您的查詢,以及:

MyCol.upsert({ userId: userId, c: C, date: date }, 
    { $set: { a: 'A', b: 'B', c: C, date: date }}); 

你甚至可能需要包括ab在你的查詢,如果他們是什麼使一個文件獨特的部分。

另外,您也可以使用.update()upsert標誌設置爲true

MyCol.update(query,modifier,{ upsert: true })