【问题标题】:MongoDB 2.6 + NodeJS can't iterate cursorMongoDB 2.6 + NodeJS 无法迭代游标
【发布时间】:2015-02-20 14:07:54
【问题描述】:

我真的不知道怎么了,请帮忙。

MongoDB 版本 2.6.7

我可以毫无问题地插入,但是查找功能非常有线,请参见下面的代码。

代码 A 运行良好。

var mongoClient = require("mongodb").MongoClient;
var express = require("express");
var app = express(); 

mongoClient.connect("mongodb://localhost:27017/feeding", function(err,database){
    if(!err){
        db.collection('test').find({}).toArray(function(err, users){
            console.log(users);
        });
        app.listen(8888, function(){
            console.log("Server Started");
        });
    }else{
        console.dir(err);
    }
});

B 代码以下 抛出'TypeError: undefined is not a function' at line 25

var mongoClient = require("mongodb").MongoClient;
var express = require("express");
var app = express(); 

mongoClient.connect("mongodb://localhost:27017/feeding", function(err,database){
    if(!err){
        var cursor = db.collection('test').find({});
        while (cursor.hasNext()) { //line 25
            console.log("printed");
        }
        app.listen(8888, function(){
            console.log("Server Started");
        });
    }else{
        console.dir(err);
    }
});

我相信它说 hasNext() 不是一个函数,但参考 MongoDB 文档http://docs.mongodb.org/manual/tutorial/iterate-a-cursor/,似乎代码没有任何问题,在这个问题上花了几个小时。有人可以给我建议吗?

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

代码 B 中的行应该在 Mongo shell 中使用,而不是在 Node.js 脚本中。为此,您需要使用 Node.js MongoDB 驱动程序。

检查光标对象here的文档。

你需要使用cursor.nextObject()方法,检查返回的对象是否为null,这表明你已经到了终点。

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    相关资源
    最近更新 更多