我试图在没有第三方依赖的情况下执行此操作,因为我认为不需要它们。请注意,根据架构师的规定,我们必须使用 MongoDB native ,而不是 Mongoose(不要问!)。
基本上,我有一个 getAll
函数,它将从单个集合中返回所有文档(基于传入的查询)。
文档的数量很容易达到数千,因此,我想在收到它们时将它们流式传输出去。
我有以下代码:
db.collection('documents')
.find(query)
.stream({
transform: (result) => {
return JSON.stringify(new Document(result));
}
})
.pipe(res);
哪种有效,除了它破坏了文档应位于的数组,并且它响应 {...}{...}
一定有办法做到这一点吗?
最佳答案
你可以做的是在请求数据库之前显式地写入数组的开头 res.write("[")
,在每个 json 上放置一个 ,
,字符串化对象并在流端写入数组的末尾 res.write("]")
这可以工作。 但不建议这样做!
JSON.stringify
is a very slow operation, you should try to use it as less as possible.
更好的方法是使用可流式 JSON.stringify 实现,例如 json-stream-stringify
const JsonStreamStringify = require('json-stream-stringify');
app.get('/api/users', (req, res, next) => {
const stream = db.collection('documents').find().stream();
new JsonStreamStringify(stream).pipe(res);
);
Be aware of using pipe in production, pipe does not destroy the source or destination stream when errors. It is advisable to go for
pump
orpipeline
in production to avoid memory leaks.
关于node.js - 将 MongoDB 结果流式传输至 Express 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53849735/