javascript - 通过 express 从 mongo 获取数据,构建对象,并发送给 React

标签 javascript node.js reactjs mongodb express

我目前陷入了异步 hell 。 在我的 React 中,我有一个页面/菜单,它将通过 expressjs api 从我的 mongo 实例加载数据。

在我的名为菜单的数据库中,我有代表膳食类型的集合,例如“早餐”、“午餐”等。在这些集合中,每个项目的文档看起来像这个面包集合示例:

{
  _id: 2398jcs9dn2f9f,
  name: "Ciabatta",
  desc: "Italian bread",
  imageURI: "image01.jpg",
  reviews: []
}

这是我的 api,将在页面加载时调用

exports.getAllFoods = (req, res, next) => {
    const db = mongoose.connection

    const allCollections = {}

    try {
        db.db.listCollections().toArray((err, collections) => {
            collections.forEach((k) => {
                allCollections[k.name] = []
            })

            Object.keys(allCollections).map(k => {
                let Meal = mongoose.model(k, MealSchema)
            
                meal = Meal.find((err, docs) => {
                    allCollections[k] = docs
                    console.log(allCollections)
                })
            })
            res.send(allCollections)
        })
    } catch (error) {
        console.log(error)
        res.send('unable to get all collections')
    }
}

console.log(allCollections) 的最后输出结果如下:

{ snacks:
   [ { review: [],
       tags: [],
       _id: 5fcec3fc4bc5d81917c9c1fe,
       name: 'Simosa',
       description: 'Indian food',
       imageURI: 'image02.jpg',
       __v: 0 } ],
  breads:
   [ { review: [],
       tags: [],
       _id: 5fcec41a4bc5d81917c9c1ff,
       name: 'Ciabatta',
       description: 'Italian bread',
       imageURI: 'image02.jpg',
       __v: 0 } ],
}

这正是我所需要的,但我一直在弄清楚如何发送到 React。我该怎么做才能发送上面的 json? res.send(allCollections) 给了我这个:

{
    "snacks": [],
    "breads": [],
    "drinks": []
}

我明白为什么要发送上述内容,但我不知道我需要做什么来解决它。

这是我对页面加载的 react

useEffect(() => {
        axios
        .get('http://localhost:8888/api/allFoods')
        .then((res) => {
            setMealTypes(res.data)
        })
        .catch((err) => [
            console.log(err)
        ])
    }, [])

最终,我需要在控制台中输出 json,因为我想遍历该数据并使用键作为标题,然后列出值数组中的值,例如

<div>
  <h2>Breads</h2>
  <img src=image01.jpg/>
  <h3>Ciabatta</h3>
  <p>Italian bread</p>
  ...
</div> 
...

我将不胜感激任何帮助,以及我应该阅读的任何文档以帮助和提高我对 javascript 的理解

最佳答案

我更愿意使用 async 来解决这个问题/awaitPromise.all , 替换了大多数回调。

因为您在遍历数组时调用数据库,所以您遇到了最烦人的回调情况:您如何发出一堆异步的东西然后得到结果?您还需要其他东西来确保在发送结果之前调用所有回调。

Async/await 意味着我们可以声明一个函数是异步的,并等待异步操作的结果。 async/await 在 JS 中很烦人,因为它抽象掉了回调,实际上在下面创建了一个 Promise。更复杂的是,async/await 并不能解决 多个 异步函数的问题,所以我们不得不再次依赖这个花哨的 Promise.all()功能结合 map - 将所需的输入数组转换为异步函数。

原文:

Object.keys(allCollections).map(k => {
  let Meal = mongoose.model(k, MealSchema)
  meal = Meal.find((err, docs) => {
    allCollections[k] = docs
    console.log(allCollections)
  })
});

建议异步/等待:

await Promise.all(Object.keys(allCollections).map(async k => {
  let Meal = mongoose.model(k, MealSchema)
  let docs = await Meal.find();
  allCollections[k] = docs;
  console.log(allCollections);
}));

另一个优点是错误处理。如果在原始示例的回调中发生任何错误,则不会在此 try/catch block 中捕获它们。 async/await 会像您预期的那样处理错误,错误最终会出现在 catch block 中。

...
      // Now that we have awaited all async calls above, this should be executed _after_ the async calls instead of before them.
      res.send(allCollections);
    })
  } catch (error) {
    console.log(error)
    res.send('unable to get all collections')
  }
}

技术上 Promise.all()返回结果数组,但我们可以忽略它,因为您正在格式化 Object无论如何。

还有很大的空间可以进一步优化。我可能会把整个函数写成这样:

exports.getAllFoods = async (req, res, next) => {
  const db = mongoose.connection.db;

  try {
    let collections = await db.listCollections().toArray();

    let allCollections = {};
    collections.forEach((k) => {
      allCollections[k.name] = [];
    })

    // For each collection key name, find docs from the database
    // await completion of this block before proceeding to the next block
    await Promise.all(Object.keys(allCollections).map(async k => {
      let Meal = mongoose.model(k, MealSchema)
      let docs = await Meal.find();
      allCollections[k] = docs;
    }));

    // allCollections should be populated if no errors occurred
    console.log(allCollections);
    res.send(allCollections);
  } catch (error) {
    console.log(error)
    res.send('unable to get all collections')
  }
}

完全未经测试。

您可能会发现这些链接比我的解释更有帮助:

https://javascript.info/async-await

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

https://medium.com/dailyjs/the-pitfalls-of-async-await-in-array-loops-cf9cf713bfeb

关于javascript - 通过 express 从 mongo 获取数据,构建对象,并发送给 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65204931/

相关文章:

javascript - 如何在 paper.js 中获取圆心?

javascript - 添加固定参数等待回调

javascript - 如何在打印时隐藏按钮菜单?

reactjs - React-player 在加载时自动播放视频,无需控件

javascript - then 函数在所有异步调用执行之前执行

javascript - 在 javascript 函数中将服务器端控件的客户端 ID 作为参数传递

javascript - 固定 header 在手机上被 chop

node.js - 从 NodeJS 服务器调用 Yeoman 命令

node.js - 错误: FAILED_PRECONDITION: no matching index found.推荐索引为:

sql - 构建查询的更智能方式