【问题标题】:Both find() and findById() in one MongoDB call一个 MongoDB 调用中的 find() 和 findById()
【发布时间】:2016-11-21 05:40:32
【问题描述】:

我想从 1 个房间中选择数据,但我还想要所有其他房间的 ID。

我这样做

const roomId = req.params.roomId;

Room.findById(roomId).then(room => {
  if (room) {
    Room.find({}).sort({ createdAt: 1 }).then(rooms => {
      if (rooms) {
        res.render()
      }
    }).catch(next);
  }
}).catch(next);

但这会导致 2 次数据库调用。

是否可以将其限制为仅 1 次调用?

我想要的房间有很多数据,我不需要为其他房间提取这些数据,因为我只需要他们的 ID。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    通过 .find() 获取所有房间,然后使用 underscore library's findWhere 函数从完整数据集中过滤出您想要的内容。 underscore 库也适用于大型数据集。

    理想情况下,代码应如下所示:

    Room.find({}).sort({ createdAt: 1 }).then(rooms => {
      if (rooms) {
        var filteredRoom = _.findWhere(rooms, {_id: roomId})
        filteredRoom = filteredRoom.pop()
        res.render()
      }
    }).catch(next);
    

    【讨论】:

    • 这个和Array.find()一样吗?如果可能,我想避免包含underscore.js
    • 是的,有点像。但是,如果您不想使用 underscore.js,请尝试在 mongodb 中使用 aggregate()。我想它会帮助你,但我不确定。您可以使用它实现查询的联合。我没有想到其他办法。
    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多