gpt4 book ai didi

javascript - 何时在 Node.js 中使用光标

转载 作者:行者123 更新时间:2023-12-03 12:11:53 24 4
gpt4 key购买 nike

何时以及为何在项目中使用 Cursor?

如果我有这个模拟代码

var mongoClient = require('mongodb').MongoClient;


mongoClient.connect('mongodb://localhost:27017/tut3',function(err,db){
if(err)throw err;

var collection = db.collection('messages');


collection.find({},{_id:true}).each(function(err,doc){
console.log("---- CLASSIC ----")
console.dir(doc);
//stuff//
});

var cursor = collection.find({},{_id:true});

cursor.each(function(err,doc){
console.log("---- CURSOR ----")
console.dir(doc);
//stuff2
});

})

例如,收集的消息很大。

//stuff//stuff2之间有什么不同

我知道如果我这样做

var cursor = collection.find({},{_id:true});

我知道当光标返回时我拥有所有文档(同步)并且它有很多 methods ,而且在 stuff 内部,查询已完成并且我拥有所有文档...

区别在哪里?什么时候使用var光标代替“经典”find

最佳答案

区别

 cursor = collection.find();

和:

collection.find().each(function(err,doc) {

基本上就是所谓的“方法链接”。这实际上只是您想要如何编写代码的意见。因此,.each() 等方法所作用的仍然只是一个可以选择在左侧返回的光标对象。

此外,在调用此类方法之前,“光标”尚未“执行”。这意味着“修饰符”可以在不执行的情况下应用,如下所示:

cursor = cursor.skip(10);
cursor = cursor.limit(100);

因为所有修饰符也会返回到左侧光标。

这本质上是“方法链接”中应用的原则,其中从左侧返回的任何“类型”都可以“链接”在右侧:

collection.find().skip(10).limit(100).each(function(err,doc) {

如果您正在处理“小”结果集,您只需在光标上调用 .toArray() 方法即可:

collection.find({},{_id:true}).toArray(function(err,array) {
console.log( array ); // everything
});

但是,如果有数千或数百万个结果,您可能不希望将所有这些结果加载到内存中。这是使用迭代器进行处理的地方:

collection.find({},{_id:true}).each(function(err,doc) {
// do something with the current doc
});

迭代是游标存在的原因。

关于javascript - 何时在 Node.js 中使用光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24927269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com