2014-09-27 56 views
-1

有沒有辦法更好地編寫這個部分?Mongodb多個運算符

'update': function (req, res) { 
    var item = req.body.item; 
    var tags = []; 
    tag.find(function (err, _tags) { 
     tags = _tags; 
     post.update({ '_id': item._id }, { $set: { Text: item.Text } }, function (e1, r1) { 
      post.update({ '_id': item._id }, { $pullAll: { Tags: tags } }, function (e2, r2) { 
       post.update({ '_id': item._id }, { $pushAll: { Tags: item.Tags } }, function (e3, r3) { 
        if (r3 === 1) { 
         res.json(true); 
        } 
       }); 
      }); 
     }); 
    }); 
} 

Post具有標籤陣列,並且我想更新標籤,我得到的所有標籤,並$pullAll他們空項目變量的數組,然後$pushAll重新填寫,我不想追加新標籤,因爲它是一個更新的方法,上面的代碼工作正常,但猜測這是一個有點不正確

+1

不會有一個'' {$ set:{Text:item.Text,Tags:item.Tags}}'做同樣的事情? – JohnnyHK 2014-09-27 13:50:10

+0

你是對的,回答,我會標記,我想我問的不正確的方式,你能告訴如何使多個操作員在1行或我應該提出新的問題? – 2014-09-27 14:11:01

+0

看到這個其他職位的後續問題:http://stackoverflow.com/questions/9823140/multiple-mongo-update-operator-in-a-single-statement – JohnnyHK 2014-09-28 14:05:51

回答

0

假設你正在試圖取代現有Tags新集,可以簡化到:

'update': function (req, res) { 
    var item = req.body.item; 
    post.update({ '_id': item._id }, 
     { $set: { Text: item.Text, Tags: item.Tags } }, 
     function (e1, r1) { 
      if (r1 === 1) { 
       res.json(true); 
      } 
     } 
    ); 
}