2016-08-22 10 views
3

jquery UIのソート可能な関数(source)を使用して要素を並べ替えます。私はそれらの要素のリストを作成するカスタムコールバックを構築しました。ですから、要素を移動すると、すべての要素に新しい位置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は

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

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

ルートを投稿しますスキーマ

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 }); 

これを達成するために他に何かが必要です。私は運が無ければgoogleを試しました。

答えて

2

あなたは、サーバーに複数の要求せずに、より良い方法で更新を実行する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); 
+0

ありがとう!私はこれを試して、あなたに戻ってきます! –

+1

この小さな調整で 'parseInt(item.id)'、 'parseInt(item.position)'を呼び出すと、コレクションから 'unique'インデックスを削除しました。ありがとうございました! –

+0

@JonathanNielsenご心配なく、喜んで助けてください。 – chridam

0

は、ここで私は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}); 

    }); 

    }); 
関連する問題