[英]How to update multiple models on mongoose and return updated models as an array?
[英]Mongoose - How to update object in array and then sort the updated array?
我有以下文件...
{
"_id": {
"$oid": "5bca528b49079d64dd4cea5d"
},
"song_queue": [
{
"song_id": "best",
"vote": 1
},
{
"song_id": "west",
"vote": 1
}
],
"room_id": "FHWAN",
"__v": 0
我的問題是,我需要首先更新其中一首歌曲的投票,然后根據投票計數重新排列數組的順序。
我有兩種單獨的查詢方式來做...
// Give the song an upvote.
await Room.findOneAndUpdate(
{ "song_queue.song_id": song.song_id },
{$set: { "song_queue.$.vote": song.votes }},
{ new: true }
);
// Sort the queue.
room = await Room.findOneAndUpdate(
{ room_id: data.room_id },
{ $push: { song_queue: { $each: [], $sort: { vote: -1 } } } },
{ new: true }
);
有沒有辦法將兩個查詢合並為一個查詢,或者使其更簡潔? 我想要一個查詢來更新song_queue
的歌曲,然后在更改后對數組進行排序。
由於無法保證保留update
參數內的操作順序,因此無法合並此查詢,因此這樣的代碼可能無法正確運行,因為您無法確定使用更新之前的song_queue.$.vote
song_queue
排序:
await Room.findOneAndUpdate(
{ "song_queue.song_id": song.song_id },
{
$set: { "song_queue.$.vote": song.votes },
$push: { song_queue: { $each: [], $sort: { vote: -1 } } }
},
{ new: true }
);
優化數據庫查詢的方法是使用有序大容量寫操作,該操作將僅一次往返MongoDB,而不是兩次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.