English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this Node.js tutorial, we will learn to use the db.createCollection() method with an example to create a collection in the MongoDB database from a Node.js application.
The following is a step-by-step guide with an example of creating a collection in MongoDB from a Node.js application.
Start the MongoDB service. Run the following command to start the MongoDB service
sudo service mongod start
Get the basic URL of the MongoDB service. To find out the basic URL of the MongoDB service, a simple trick is to open the terminal and run the Mongo Shell.
Terminal - Mongo Shell
arjun@nodejs:~$ mongo MongoDB shell version v3.4.9 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.9 Server has startup warnings: 2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]
When the Mongo Shell starts, it echoes the basic URL of MongoDB.
mongodb://127.0.0.1:27017
Prepare the complete URL. Attach the name of the database you want to connect to (e.g., newdb) to the base URL.
mongodb://127.0.0.1:27017/newdb
Create a MongoClient.
var MongoClient = require('mongodb').MongoClient;
Connect to the MongoDB server with the help of the URL.
MongoClient.connect(url, <callback_function>);
Once the attempt to establish a connection with MongoClient is completed, the callback function will receive an error and a db object as parameters.
If the connection is successful, the db object points to the database newdb.
Create a MongoDB collection in the database. The following is the syntax for the createCollection() method used to create a collection in MongoDB from Node.js.
db.createCollection(<collection_name>, <callback_function>)
Parameter Description:
collection_name - The name of the new MongoDB collection we want to create
callback_function - After Node.js attempts to create a collection and prepares the result, this Node.js callback function will be called. The callback function receives an error and a result object as parameters.
node-js-mongodb-create-collection.js
// We create a user collection in the newdb database. var url = "mongodb://localhost:27017/newdb //Create a client to mongodb var MongoClient = require('mongodb').MongoClient; //Connect the client to the mongo service MongoClient.connect(url, function(err, db) { if (err) throw err; //db pointing to newdb console.log("Switched to "+db.databaseName+"database"); //Create a user collection in the database db.createCollection("users", function(err, result) { if (err) throw err; console.log("Collection is created!"); //Close the connection with db after completion db.close(); }); });
Output Result
arjun@tutorialkart:~/workspace/nodejs/mongodb$ node node-js-mongodb-create-collection.js Switched to newdb database Collection is created!