找不到nodejs集合中的mongo

我连接到数据库并接收客户端。 下一步是创build一个集合(表)。

db.createCollection("test", function(err, collection){ //I also tried db.collection(... if(collection!=null) { collection.insert({"test":"value"}, function(error, model){console.log(model)}); } else if(err!=null) console.log(err); }); 

现在我将创build一个集合“test”以及一个文档(行)“test”。

接下来是获取集合的内容:

 db.test.find({}); //An empty query document ({}) selects all documents in the collection 

在这里我得到的错误:不能调用未定义的“查找”。 那么,我做错了什么?

编辑:我这样连接到数据库:

 var mongoClient = new MongoClient(new Server("localhost", 27017, {native_parser:true})); mongoClient.open(function(err,mongoclient){ if(mongoclient!=null) { var db = mongoclient.db("box_tests"); startServer(db); } else if(err!=null) console.log(err); }); 

在mongo命令行中,您可以使用db.test.find({})但是在JavaScript中,目前还没有办法复制那个接口(也许有一天和谐代理)。

所以它会抛出一个错误无法调用未定义的“查找”,因为在db中没有testing

mongodb的node.js驱动程序的api是这样的:

 db.collection('test').find({}).toArray(function (err, docs) { //you have all the docs here. }); 

另一个完整例子:

 //this how you get a reference to the collection object: var testColl = db.collection('test'); testColl.insert({ foo: 'bar' }, function (err, inserted) { //the document is inserted at this point. //Let's try to query testColl.find({}).toArray(function (err, docs) { //you have all the docs in the collection at this point }); }); 

另外请记住,mongodb是无模式的,你不需要提前创build集合。 有几个特定的​​情况下,像创build一个封顶收集和其他几个。

如果在db.createCollection块后面调用db.test.find“next”,它会在db.createCollection成功之前立即结束。 所以在这一点上,db.test是不确定的。

请记住,该节点是asynchronous的。

为了得到我期望的结果,db.test.find必须位于调用console.log(model)的collection.insertcallback中。

 db.createCollection("test", function(err, collection){ if(collection!=null) { // only at this point does db.test exist collection.insert({"test":"value"}, function(error, model){ console.log(model) // collection and inserted data available here }); } else if(err!=null) console.log(err); }); // code here executes immediately after you call createCollection but before it finishes 

检出节点async.js模块。 这里好写生: http : //www.sebastianseilund.com/nodejs-async-in-practice