【问题标题】:Mongoose findOne method inside parent find method父查找方法中的猫鼬 findOne 方法
【发布时间】:2021-06-27 05:10:03
【问题描述】:

我正在尝试通过订单文档给出的 restaurantId 获取餐厅名称。

问题:Restaurant.findOne() 返回一个未解决的 Promise。我无法异步运行 find 方法。

Order.find({ customerId: userId })
    .exec()
    .then((docs) => {
      res.status(200).json({
        count: docs.length,
        orders: docs.map((doc) => {
          let rest = Restaurant.findOne({ doc.restaurantId }).exec();

          return {
            _id: doc._id,
            restaurantName: rest,
            itemTotal: doc.items.length,
            timestamp: doc.timestamp,
            orderStatus: doc.orderStatus,
          };
        }),
      });
    });
};

【问题讨论】:

  • 您可以尝试先将 Order.find 的输出放入一个数组中。然后,迭代数组,以查询餐厅。或者,您可以使用聚合 $lookup 在单个查询中返回结果。

标签: node.js mongodb mongoose


【解决方案1】:

首先,map 不允许对 Promise 进行迭代。它不会等待承诺完成并继续进行下一次迭代。你应该使用forof。像这样:

Order.find({ customerId: userId })
    .exec()
    .then(async (docs) => {
      const orders = [];
      for (const doc of docs) {
        let rest = await Restaurant.findOne({ id: doc.restaurantId }).exec();
        orders.push({
          _id: doc._id,
          restaurantName: rest,
          itemTotal: doc.items.length,
          timestamp: doc.timestamp,
          orderStatus: doc.orderStatus,
        })
      }
      res.status(200).json({
        count: docs.length,
        orders,
      });
    });

您的代码中的另一个问题是:

let rest = Restaurant.findOne({ doc.restaurantId }).exec();

应该是:

let rest = Restaurant.findOne({ id: doc.restaurantId }).exec();

【讨论】:

  • 工作就像一个魅力大声笑.. 非常感谢(不知道承诺不会在地图上得到解决)
  • 您可以为答案投票并将答案标记为已接受;)谢谢
【解决方案2】:

更好的解决方案是在聚合中进行 $lookup

Order.aggregate()
.match({ customerId: userId })
.lookup({
   from: 'restaurants' ,
   localField: 'restaurantId', 
   foreignField: 'id' ,
   as: 'orders', 
})

如果您只需要显示订单中的一些数据,则需要更改为在聚合调用中定义管道并抛出 $projection。

这将允许所有数据库完成所有工作,并且只调用数据库 1 次,而不是每个订单调用 1 次,然后每个订单调用一次。

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2018-02-27
    • 2020-08-30
    • 2012-09-01
    • 2021-08-03
    相关资源
    最近更新 更多