'How to receive a stream from MongoDB using NODE.JS
I have this awesome nodejs code that connects to mongodb using mongoose and returns the json data to the client. Please note that there is an .toArray() at the end of the DB command, which means that all the results must be recived from the DB, before it can do to .toArray() and return.
My question is, how to change the below code, so that it returns a stream instead? Imagine that the returned data is very large, gigabytes in size, so that it is impossible to contain it inside the memory. The goal is to receive a continues stream of data from mongodb and forward it to the HTTP response stream, without buffering.
const mongoose = require('mongoose');
await mongoose.connect(uri)
.catch((err) => console.log(err));
if (mongoose.connection.readyState == 1) {
try {
var response = await mongoose.connection.db
.collection('newstuff')
.find(filter)
.sort(sort)
.toArray();
res.end(response);
}
catch (e) {
res.end(JSON.stringify({ error: e }));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
