Edit : добавлен настраиваемый шаг преобразования в строку.
Объект res
в ExpressJS является подклассом с возможностью записи из http.ServerResponse , и может передаваться по конвейеру.
Я обычно подключаю этот поток данных, используя встроенную поддержку NodeJS 'для преобразования итератора в читаемый и использую stream.pipeline
для обработки исключений.
Обратите внимание, что больше нет необходимости преобразовывать курсор в читаемый в NodeJS v13 +, поскольку stream.pipeline теперь принимает асинхронные c итераторы вместо потока.
Обратите внимание, что использование stringify()
излишне, если возможно напрямую использовать Mon goose s Lean () . Lean выдаст JSON данных.
import stream from "stream";
import util from "util";
function handler(req, res, next){
try {
// init the cursor
const cursor = Comment.find().lean(); // "lean" will emit json data
const readable = stream.Readable.from( cursor );
// promisifying the pipeline will make it throw on errors
await util.promisify(stream.pipeline)( readable, res.type('json') );
next();
}
catch( error ){
next( error );
}
}
С настраиваемой строковой настройкой в NodeJS v13 +:
import stream from "stream";
import util from "util";
function handler(req, res, next){
try {
// init the cursor
const cursor = Comment.find().lean(); // "lean" will emit json data
const readable = stream.Readable.from( cursor );
// promisifying the pipeline will make it throw on errors
await util.promisify(stream.pipeline)(
readable,
// Custom "stringifying" using an async iterator
async function*( source ){
// Add some output before the result from mongodb. Typically, this could be information about
// the number of results in a REST API.
yield "Appended"
for await (const comment of source ){
// Emit a "projection" of the data retrieved from MongoDB
yield {
text: comment.text,
// Add a new property:
newProperty: true
}
}
// Add some final data to the response. In a REST API, this might be the closing bracket of an array "]".
yield "Prended"
},
// the stringified data is then piped to express' res object
res.type('json')
);
next();
}
catch( error ){
next( error );
}
}