// we create 'users' collection in newdb database
var url = "mongodb://localhost:27017/testdb";
// create a client to mongodb
var MongoClient = require('mongodb').MongoClient;
// make client connect to mongo service
MongoClient.connect(url, function(err, db) {
if (err) throw err;
// db pointing to newdb
console.log("Switched to "+db.databaseName+" database");
// documents to be inserted
var docs = [{ name: "Udat", age: "21" },
{ name: "Karthik", age: "24" },
{ name: "Anil", age: "23" }];
// insert multiple documents to 'users' collection using insertOne
db.collection("users").insertMany(docs, function(err, res) {
if (err) throw err;
console.log(res.insertedCount+" documents inserted");
// close the connection to db when you are done with it
db.close();
});
});
위와 같은 소스를 실행 하면 TypeError: db.collection is not a function
buster@MDCT:~/node_project/mongo_test/db$ node db_insert_many.js
Switched to undefined database
/home/buster/node_modules/mongodb/lib/mongo_client.js:815
throw err;
^
TypeError: db.collection is not a function
at /home/buster/node_project/mongo_test/db/db_insert_many.js:19:8
at result (/home/buster/node_modules/mongodb/lib/utils.js:414:17)
at executeCallback (/home/buster/node_modules/mongodb/lib/utils.js:406:9)
at /home/buster/node_modules/mongodb/lib/mongo_client.js:273:5
at connectCallback (/home/buster/node_modules/mongodb/lib/mongo_client.js:955:5)
at /home/buster/node_modules/mongodb/lib/mongo_client.js:812:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
buster@MDCT:~/node_project/mongo_test/db$ npm install mongodb@2.2.33 --save
buster@1.0.0 /home/buster
└─┬ mongodb@2.2.33
├── es6-promise@3.2.1
├── mongodb-core@2.1.17
└─┬ readable-stream@2.2.7
├── buffer-shims@1.0.0
├── core-util-is@1.0.2
├── isarray@1.0.0
├── process-nextick-args@1.0.7
├── string_decoder@1.0.3
└── util-deprecate@1.0.2
npm WARN buster@1.0.0 No description
npm WARN buster@1.0.0 No repository field.
buster@MDCT:~/node_project/mongo_test/db$ node db_insert_many.js
Switched to testdb database
3 documents inserted
TypeError: db.collection is not a function