2016-03-23 39 views
1

我有一個標籤一個蒙戈收集和數組中的所有項目時,用戶輸入的標籤我想做以下的數組:MongoDB中是否存在和更新其他插入

如果陣列中的一個標籤存在,更新計數 如果陣列中的一個標籤不存在,插入帶的0

我現在有一個計數:

QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} }, { upsert: true }); 

QuestionTags是爲DB收集貓鼬架構。

這似乎沒有工作。我輸入了一個新的標籤數組,並且他們沒有被添加,並且現有的標籤沒有增加。

有沒有辦法處理這個問題,而不必循環通過tagArray併爲數組中的每個項目進行數據庫調用?

UPDATE: 改變了我的代碼,這

QuestionTags.update({'tag': {$in: req.body.tags}}, {$inc : {'count': +1} }, { upsert: true, multi: true }); 
QuestionTags.find({'tag' :{$nin: req.body.tags}}, function(err, newTags) { 
    console.log("New Tags :" + newTags); 
    var tagArray = []; 
    newTags.forEach(function(tag){ 
     var tagObj = { 
      tag: tag, 
      count: 1 
     } 
     tagArray.push(tagObj); 
    }); 
    QuestionTags.collection.insert(tagArray); 
}); 

然而,newTags爲空。 QuestionTags集合目前是空的,因此它不應該爲空。

+0

什麼是你的tagArray?簡單字符串?我只是做了一個測試,並增加了更新查詢。對於插入,您的更新對象(update的第二個參數)中沒有'$ set:{tag:'newTag'}',所以upsert實際上並沒有插入任何東西。 – Komo

+0

@Komo是它的簡單字符串[「Java」,「JavaScript」,「敏捷」]。如果一切正常,您可以使用正確的方式發佈解決方案 – erichardson30

+0

@Komo做了您發佈的解決方案無效嗎? – erichardson30

回答

1

我認爲你可以在幾個查詢中做到這一點,而不用查詢循環。

1)更新現有的標籤數:您的查詢工作:

QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} },{multi: true}); 

2)尋找新的標籤:

QuestionTags.find({},function(err, tags) { 
    var newTagObj = []; 

    // tags is originally an array of objects 
    // creates an array of strings (just tag name) 
    tags = tags.map(function(tag) { 
     return tag.tag; 
    }); 

    // returns tags that do not exist 
    var newTags = tagArray.filter(function(tag) { 
     // The count = 1 can be done here 
     if (tags.indexOf(tag) < 0) { 
      tag.count = 1; 
     } 

     return tags.indexOf(tag) < 0; 
    }); 

    // creates tag objects with a count of 1 
    // adds to array 
    // (this can be done in the previous loop) 
    newTags.forEach(function(tag) { 
     var tagObj = { 
      tag: tag, 
      count: 1 
     } 
     newTagObj.push(tagObj); 
    }); 

這會給你的是不存在數據庫中標記的數組。

3)使用2的結果,在find回調插入新標籤:

QuestionTags.collection.insertMany(newTagObj); 
+0

總的來說,這個方法非常有效。但是,計數似乎沒有更新。每次即使標籤具有相同的「標籤」屬性,也只是插入新記錄。 – erichardson30

+0

嗯,你在更新查詢中刪除了upsert選項嗎?至少不應該添加新記錄。 – Komo

+0

是的更新查詢是相同的。不知道爲什麼它不起作用。我在更新之前,在過濾器之前註銷了tagArray,然後是新標籤,它們都包含相同的項目 – erichardson30