使用不同的值更新多个文档

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)

我必须有其他的东西来实现这一目标.我试过谷歌没有任何运气.

chr*_*dam 5

您可以尝试使用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)

  • @VinceBowdren 我想“当然,如果你想对它们进行排序,你不想拥有相同的位置编号”所以在我的模式中我做了`{ type: Number, unique: true }`。但是当我使用批量更新时,一些位置在其他位置之前发生了变化,因此两个文档可能在一秒钟内具有相同的位置编号。我转到 mongo shell 并执行 `db.collection.getIndexes()` 来列出索引。我找到了我的唯一位置索引并通过执行`db.collection.dropIndex('position_1')` 将其删除。`position_1` 是我的索引的名称。在此之后,我还切换到了我上面写的架构设置。 (2认同)