使用流进行 Mongoose 查询真的值得吗?

1 mongoose mongodb node.js express

如果我有这样的查询:

//sample 1 conventional querying
const response =  await Events.find({data: {$gt: new Date('2019-12-01')}})
res.json(response)

//sample 2 using stream
Events.find({data: {$gt: new Date('2019-12-01')}})
    .cursor()
    .pipe(JSONStream.stringify())
    .pipe(res.type('json'))

Run Code Online (Sandbox Code Playgroud)

我什么时候应该使用每一个?使用流媒体有什么优势?

Ash*_*odi 6

那么最简单的解释是 -

当您从查找查询返回的数据很少时 - 您可以考虑将其加载到内存中并使用它。

当你有大量数据时 - 你应该使用流,这样你就不需要将完整的数据存储在内存中,这可能会使nodejs抛出out of memoruy异常。您可以覆盖它,但这不是一个好主意。

希望它能清除。