node.js - 将 MongoDB 结果流式传输至 Express 响应

标签 node.js mongodb express

我试图在没有第三方依赖的情况下执行此操作,因为我认为不需要它们。请注意,根据架构师的规定,我们必须使用 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 or pipeline in production to avoid memory leaks.

关于node.js - 将 MongoDB 结果流式传输至 Express 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53849735/

相关文章:

node.js - 为什么node-webkit中的errno与Node.js不同?

node.js - 将可写流扩展为转换流?

css - 如何使用 gulp-clean-css 编写一个新的 -min.css 文件而不是默认覆盖现有的 css 源文件?

javascript - 无法从 Nodejs 中的 API URL 获取图像文件

rest - channel :mychannel received discovery error:access denied Failed to evaluate transaction: Error: DiscoveryService: mychannel error: access denied

node.js - Electron 关闭按钮不起作用

javascript - NowJS - 客户端/浏览器通信(无需联系 "everyone")

mongodb - 更新 mongodb 依赖后出现警告

java - Mongo hadoop mapreduce 显示错误

javascript - 针对字符串测试子字符串数组