var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
insertDocuments(db, function() {
db.close();
});
});
var insertDocuments = function(db, callback) {
var collection = db.collection('test');
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
When run this code I'm getting error 'TypeError: db.collection is not a function'
/home/sys2079/IdeaProjects/mongo_test/node_modules/mongodb/lib/mongo_client.js:797 throw err; ^ TypeError: db.collection is not a function at insertDocuments (/home/sys2079/IdeaProjects/mongo_test/test.js:17:23) at /home/sys2079/IdeaProjects/mongo_test/test.js:10:3 at args.push (/home/sys2079/IdeaProjects/mongo_test/node_modules/mongodb/lib/utils.js:431:72) at /home/sys2079/IdeaProjects/mongo_test/node_modules/mongodb/lib/mongo_client.js:254:5 at connectCallback (/home/sys2079/IdeaProjects/mongo_test/node_modules/mongodb/lib/mongo_client.js:933:5) at /home/sys2079/IdeaProjects/mongo_test/node_modules/mongodb/lib/mongo_client.js:794:11 at _combinedTickCallback (internal/process/next_tick.js:131:7) at process._tickCallback (internal/process/next_tick.js:180:9)
what i have to do ? I'm very new to mongodb
Thanks in advance
When run this code I’m getting error ‘TypeError: db.collection is not a function’
Hi Asha,
Which version of mongodb
npm module are you using ?
You can check the version either in the project package.json
or node_modules/mongodb/package.json
.
If you are using version >=3.0, the variable returned by MongoClient
has been modified to return a client object now.
For example, your code example should look as below:
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server"
);
/* Pass a selected database */
insertDocuments(client.db('nodejs'), function() {
client.close();
});
});
Please see also MongoDB Node.js driver changes 3.0.0 for more features/changes.
what i have to do ? I’m very new to mongodb
Based on the code snippet you posted, it seems that you’re following the MongoDB Node.js QuickStart for v2.2.
If you would like to follow this specific version of the tutorial please use version 2.2.
You can do this by performing
npm install mongodb@2.2 --save
Instead of below as shown in the tutorial page
// Below means download the latest version
npm install mongodb --save
There is an incoming update for the QuickStart docs for changes in v3.0.0.
Regards,
Wan.