db.createCollection is not a function

2020-06-01 08:53发布

问题:

I am attempting to create a mongo instance however I am unable to access any of the helper methods from the mongodb nodejs driver.

My mongo instance is running within docker and the ports have been opened up to my local.

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)

Copied from 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();
    });
});

No error is returned through the run, and no methods are exposed on the db object.

any ideas?

回答1:

According to the changelog for Mongodb 3.0 you now get a client object containing the database object instead:

So you need the db object that points to the database you want to use, in your case mydb. Try this:

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
    });
});


回答2:

You're not the one facing this issue. Seems that 3.0 mongo driver has a bug or these are just breaking backwards compatibility changes. Take a look here: db.collection is not a function when using MongoClient v3.0

To use DB name in the URL, you need to uninstall MongoDB, change to "mongodb": "^2.2.33" in dependencies and do npm install to install the new version.

Or you can install specific version with command npm install mongodb@2.2.33 --save