首页 > 解决方案 > 在 Node/Express API 上的连接之间保持数据

问题描述

我正在为 MongoDB 构建一个 Node/Express API 前端,它对于单个连接都可以正常工作,但对于 2 个或更多则不行。

如果我同时使用 2 个连接调用 API,则被调用函数中的数据会损坏。代码摘录:

// This is the Express entry point
app.get('/user', async (request, response) => {
    const readResp = await read(request)
    response.send(readResp)
})


// The called function
async function read(request) {
    //
    try {

        // This gets data from MongoDB via Mongoose
        var connections = await Connection.find() 

        // Do other stuff here with connections,
        // but part-way through the connections 
        // variable gets corrupted as the new request has come in

        return { error: { code: 0, message: 'OK' }, connections: connections }
    } catch (error) {
        Log.errorToConsoleAndClose(error)
    }
}

我使用 express 来等待传入的请求,触发read()函数并返回响应。

当第二个请求同时进来时,问题就出现了,因为它似乎没有使用新的实例,read()而是我的代码在某个时候失败,因为 varconnections被新的传入请求重置。

任何线索/帮助将不胜感激。

标签: node.jsexpress

解决方案


我遇到了与使用 async 的其他数据库类似的东西

解决方案是在异步请求之外创建连接,使其保持打开状态,然后通过 .

发生的事情是每次调用异步时都会重置连接而不是完成请求

解决方案之一是使用.thenpromises

这是一个使用 Promise 的例子。

  router.post('/api/get_data', (req, res, next) => {
  try {
  MongoClient.connect(connectionStr, mongoOptions, function(err, client) {
   assert.equal(null, err);
   const db = client.db('db');

   //Step 1: declare promise

   var myPromise = () => {
     return new Promise((resolve, reject) => {

        db
         .collection('your_collection')
         .find({id: 123})
         .limit(1)
         .toArray(function(err, data) {
             err 
                ? reject(err) 
                : resolve(data[0]);
           });
     });
   };

   //Step 2: async promise handler
   var callMyPromise = async () => {

      var result = await (myPromise());
      //anything here is executed after result is resolved
      return result;
   };

   //Step 3: make the call
   callMyPromise().then(function(result) {
      client.close();
      res.json(result);
   });
 }); //end mongo client


 } catch (e) {
  next(e)
 }
});
module.exports = router;

有关该主题的更多信息,请参见Async MongoDB


推荐阅读