Node.js:为了通过mongoDB集合进行查询需要什么?

我完全是新的节点和mongoDB,所以请裸露在我身边。 我会尽我所能,尽可能清楚地解释我所遇到的问题。

我在Ubuntu上运行mongoDB。 我有一个名为“临时”的数据库。 在那个数据库里面我有一个名为'questions'的集合。

在命令行中使用mongo,我能够成功地将对象插入到“问题集合”中。 到现在为止还挺好。 我的下一步是用JavaScript编写一个程序,它将运行并向集合中插入更多的对象。 这工作得很好,我能够连接到我的collections,并添加更多。

现在,这是我遇到问题的地方。 在JavaScript程序中,我想从我的“问题”集合中查询和检索某些数据。 我的代码如下所示:

var mc = require('mongodb').MongoClient; //connect to database db = mc.connect('mongodb://localhost/temporary', function(err,db){ var myCollection = db.collection('questions'); var newArray = myCollection.find().toArray(); db.close(); } 

我相信我正确连接到我的集合,因为这是我连接到它添加条目。 我的问题是find()方法和toArray()方法。

从我的理解find()让我通过我的集合进行search,最终返回一个称为游标的东西。 我想要把这些对象,并使用toArray()把它们放到一个数组中。

问题是这行给了我一个错误:

 var newArray = myCollection.find().toArray(); 

错误说“错误:callback是强制性的”。 所以我结束了search,并find了这个网站: http : //mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html

从那里我决定尝试:

  var newArray = myCollection.find().toArray(function(err, items){ if(err){ console.log("An error occured");}}); 

有了这个,我不断收到“出现错误”,打印出来。 有谁知道这个问题可能是什么? 这显然与toArray()方法,但我不知道错误的原因是什么。 我觉得我的代码现在几乎就是那些枯燥的骨头,而且我不能为了我的生活而弄清楚我做错了什么。

澄清,当我只是做find()方法本身,但由于某种原因添加.toArray()打破我的代码,我没有得到任何错误。 我想这也许是因为我的find()调用有参数,但即使在search我知道在集合中的对象时也会得到相同的错误,所以不是这样。

我正在连接到我的数据库。 我创build了一个已经存在的“问题”集合,并且插入了一些对象。 我使用find()来做一个查询,尝试将对象检索到一个数组中,然后我想closures数据库。

有什么build议么? 任何帮助真的很感激。 对不起,冗长的问题。

更改

我希望这可以帮助你..

  MongoClient.connect("mongodb://localhost:27017/temporary", function(err, db) { var myCollection = db.collection('questions'); myCollection.find().toArray(function(err,resu) { console.log(resu); } ); 

你可以尝试重构和testing你的代码,如下所示:

 var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server, assert = require('assert'); var db = new Db('temporary', new Server('localhost', 27017)); // Establish connection to db db.open(function(err, db) { var myCollection = db.collection('questions'); // Retrieve all the documents in the collection myCollection.find().toArray(function(err, documents) { if(err){ console.log("An error has occurred"); } assert.equal(1, documents.length); db.close(); }); });