代码之家  ›  专栏  ›  技术社区  ›  buydadip

Mongoose-如何更新数组中的对象,然后对更新后的数组进行排序?

  •  0
  • buydadip  · 技术社区  · 6 年前

    {
    "_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 然后在更改后对数组进行排序。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Volodymyr    6 年前

    无法合并此查询,因为内部操作的顺序 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 }
    );
    

    优化数据库查询的方法是使用 Ordered Bulk Write 只有一次往返MongoDB而不是两次。