我正在尝试创建mongo实例,但是无法从mongodb nodejs驱动程序访问任何帮助程序方法。

我的mongo实例正在docker中运行,并且端口已向我的本地开放。

TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

从w3schools复制...
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    db.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();
    });
});

运行不会返回任何错误,并且db对象上没有公开任何方法。

有任何想法吗?

最佳答案

根据Mongodb 3.0的changelog,您现在将获得一个包含数据库对象的客户端对象:

因此,您需要db对象,该对象指向要使用的数据库,在本例中为mydb。试试这个:

var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {   //here db is the client obj
    if (err) throw err;
    var dbase = db.db("mydb"); //here
    dbase.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();   //close method has also been moved to client obj
    });
});

09-26 04:51
查看更多