Jon*_*sen 5 javascript mongoose mongodb node.js
我正在使用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
}]
Run Code Online (Sandbox Code Playgroud)
我通过做一个简单的Ajax帖子将这个列表发送到我的后端
$.post('/position', { data: list });
Run Code Online (Sandbox Code Playgroud)
路线
router.post('/position', (req, res) => {
console.log(req.body.data); // This prints the array of objects above.
});
Run Code Online (Sandbox Code Playgroud)
架构
mongoose.Schema({
id: Number,
position: Number,
...
});
Run Code Online (Sandbox Code Playgroud)
现在我无法弄清楚如何有效地改变所有文件的位置.创建一个糟糕的数组循环并执行多个数据库请求不是最好的方法.
我在这里试过,这感觉很错.
for (let i in req.body.data) {
collection.update({ id: req.body.data[i].id }, { position: req.body.data[i].position });
Run Code Online (Sandbox Code Playgroud)
我必须有其他的东西来实现这一目标.我试过谷歌没有任何运气.
您可以尝试使用bulkWriteAPI 以更好的方式执行更新,而无需向服务器发出多个请求:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1068 次 |
| 最近记录: |