Nodejs Create Database Mongodb Free pdf.2933
Nodejs Create Database Mongodb Free pdf.2933
In this Node.js Tutorial, we shall learn to Create Database in MongoDB from Node.js Application with an
example.
Example
Following is a step by step guide with an example to create a database in MongoDB from Node.js Application.
1. Start MongoDB Service. Run the following command to start MongoDB Service
sudo service
mongod start
2. Install mongodb package using npm. Refer Node.js MongoDB Tutorial to install mongodb package.
3. Get the base URL to MongoDB Service. A simple hack to know the base url of MongoDB Service is to Open a Terminal and
run Mongo Shell.
Terminal - Mongo Shell
arjun@nodejs:~$
mongo
MongoDB shell version
v3.4.9
connecting to: mongo
arjun@nodejs:~$
mongodb://127.0.0.1:2
MongoDB shell version v3.4.9
7017
MongoDB
connectingserver
to: mongodb://127.0.0.1:27017
version: 3.4.9
MongoDB
Server has server
startupversion: 3.4.9
warnings:
Server has startup warnings:
2017-10-
29T18:15:36.110+0530
2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]
I STORAGE
[initandlisten]
While the Mongo Shell starts up, it echoes back the base url of MongoDB.
mongodb://127.0.0.1:2
7017
mongodb://127.0.0.1:27017
4. Prepare the complete URL. Append the Database name you want to create (say newdb), to the base URL.
mongodb://127.0.0.1:2
7017/newdb
mongodb://127.0.0.1:27017/newdb
5. Create a MongoClient.
var MongoClient =
require('mongodb').Mon
goClient;
6. Make connection from MongoClient to the MongoDB Server with the help of URL. [Note : In MongoDB, creating Database is
an implicit process.]
MongoClient.connect(u
rl,
<callback_function>);
MongoClient.connect(url, <callback_function>);
Once the MongoClient is done trying to make a connection, the callback function receives error and db object as arguments.
If the connection is successful, the db object points to the newly created database newdb.
arjun@tutorialkart:~/w
orkspace/nodejs/mong
odb$ node node-js-
arjun@tutorialkart:~/workspace/nodejs/mongodb$ node node-js-mongodb-create-database.js
Database created!
db object points to the database : newdb
Reference
MongoDB Tutorial – Learn MongoDB from basics with Examples.
Conclusion :
In this Node.js MongoDB tutorial : Node.js – Create Database in MongoDB, we have learnt to create a
database from Node.js Application using mongodb package. In our next tutorial – Node.js MongoDB Drop
Database, we shall learn to delete the database.
Node.js
⊩ Node.js Tutorial
⊩ Node.js - Modules
⊩ Node.js - forEach
Express.js
⊩ Express.js Tutorial
⊩ What is Express.js?
⊩ Install Express.js
⊩ Express.js Routes
⊩ Express.js Middleware
⊩ Express.js Router
Node.js Buffers
Node.js Buffers
Node.js HTTP
Node.js MySQL
⊩ Node.js MySQL
Node.js MongoDB
⊩ Node.js MongoDB
Node.js Mongoose
⊩ Node FS
Node.js JSON
Node.js Examples
⊩ Node.js Examples
Useful Resources