簡體   English   中英

使用不同的值更新多個文檔

[英]Updating multiple documents with different values

我正在使用jquery ui的可排序函數( )來重新排列元素。 我已經構建了自定義回調來創建這些元素的列表。 所以當我移動一個元素時,所有元素都會被賦予一個新的位置id。 它可能看起來像這樣:

[{
    id_of_element_in_database: 12,
    new_position: 0
}, {
    id_of_element_in_database: 16,
    new_position: 1
}, {
    id_of_element_in_database: 14,
    new_position: 2
}]

我通過做一個簡單的Ajax帖子將這個列表發送到我的后端

$.post('/position', { data: list });

路線

router.post('/position', (req, res) => {
    console.log(req.body.data); // This prints the array of objects above.
});

架構

mongoose.Schema({
    id: Number,
    position: Number,
    ...
});

現在我無法弄清楚如何有效地改變所有文件的位置。 創建一個糟糕的數組循環並執行多個數據庫請求不是最好的方法。

我在這里試過,這感覺很錯。

for (let i in req.body.data) {
    collection.update({ id: req.body.data[i].id }, { position: req.body.data[i].position });

我必須有其他的東西來實現這一目標。 我試過谷歌沒有任何運氣。

您可以嘗試使用bulkWrite API以更好的方式執行更新,而無需向服務器發出多個請求:

var callback = function(err, r){
    console.log(r.matchedCount);
    console.log(r.modifiedCount);
}
// Initialise the bulk operations array
var ops = req.body.data.map(function (item) { 
    return { 
        "updateOne": { 
            "filter": { 
                "id": parseInt(item.id),
                "position": { "$ne": parseInt(item.position) }
            },              
            "update": { "$set": { "position": parseInt(item.position) } } 
        }         
    }    
});

// Get the underlying collection via the native node.js driver collection object
Model.collection.bulkWrite(ops, callback);

以下是我使用Node.js的方法:

var forEach = require('async-foreach').forEach;
var bulk = Things.collection.initializeOrderedBulkOp();


  Things.find({}).lean().execAsync(execSettings).then(function(resp){

    forEach(resp, function(template, index, arr) {

      var done = this.async();

      bulk.find({'_id': template._id}).update({$set: {_sid: generateShortId()}});
      bulk.execute(function (error) {
           done();                  
      });

    }, function(notAborted, arr){

        res.json({done: true, arr: arr.length});

    });

  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM