【问题标题】:promise all mongoose find return incomplete value承诺所有猫鼬找到返回不完整的值
【发布时间】:2020-07-21 10:07:41
【问题描述】:

我尽一切努力从两个查询中创建一个 Promise 循环。我做了一个查询来调用另一个查询。但是返回的值只会返回第一个查询。我不能把这两者结合起来。这是我的代码

 exports.beschikbaarheid = function (req, res, next) {
  const { leverancier, start, eind } = req.body;
  Categorie.find({
    leverancier: leverancier,
  })
    .exec()
    .then((result) => {
      return Promise.all(
        result.map(async (record) => {
          const voor = await Voorraad.find({
            categorie: record._id,
          }).exec();
          record.voorraad = voor;
          return record;
        })
      ).then((results) => {
        res.json({
          results,
        });
      });
    })
};

当我返回记录时,它只会返回“Categorie.find”的查询当我只返回“voor”时,它将返回来自“Voorraad”的所有值以及来自“Categorie”的组,但该值不会联系“类别”中的任何数据

【问题讨论】:

    标签: javascript mongoose promise async-await


    【解决方案1】:

    在这种情况下,您应该改用$lookup。像这样的:

    Categorie.aggregate([
      {$match: {leverancier: leverancier}},
      {
        $lookup: {
          from: "voorraads", // collection of model Voorraad
          localField: "_id",
          foreignField: "categorie",
          as: "voorraad"
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 2019-02-13
      • 2018-08-19
      • 2021-12-04
      • 2017-07-10
      • 2015-04-07
      • 2015-05-12
      • 2020-12-24
      相关资源
      最近更新 更多