node.js - 在 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
被新的传入请求重置。
任何线索/帮助将不胜感激。
解决方案
我遇到了与使用 async 的其他数据库类似的东西
解决方案是在异步请求之外创建连接,使其保持打开状态,然后通过 .
发生的事情是每次调用异步时都会重置连接而不是完成请求
解决方案之一是使用.then或promises
这是一个使用 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
推荐阅读
- r - 因果影响包:根据模型估计计算后尾区概率
- sql - 根据另一列中的值更改聚合函数内的值?
- angular - 如何以角度在子组件中加载引导程序?
- java - org.apache.jasper.JasperException:在第 [23] 行处理 JSP 页面 [/ch3/dataBean/Edit.jsp] 时发生异常
- django-2.0 - 当 AppDirs 在 Django 中设置为 True 时,我可以在哪里放置模板加载器 - Django-admin-tools
- jquery - 窗口大小调整导致使用 requestAnimationFrame 的滚动动画上的元素未对齐
- cpu - 有没有办法在所有进程中跟踪寄存器?
- angular - 从 Django Rest 框架将经过身份验证的用户传递给 SendBird
- javascript - ReactJS 使 prop 成为状态
- sql - 无法转换为类型别名