Connecting Mongo DB with NodeJS
To use mongo Db with the Node here we can use Mongoose npm package and mlab.com as mongo db cloudeservice provider.
Create an account in mlab.com
Select "Create new" in MongoDB Deployments
Click on free "Sandbox" account plan
Enter the Database name for example "diary"
DB has been created
Highlighted text shows the DB URI link by which we can connect with DB.
- Setup the mlab account
Create an account in mlab.com
Select "Create new" in MongoDB Deployments
Click on free "Sandbox" account plan
Enter the Database name for example "diary"
DB has been created
Highlighted text shows the DB URI link by which we can connect with DB.
Now install mongoose package in Node Js by npm install mongoose --save in CLI
Node js code is below to connect Node Js with Mongo DB.
In below code we will create two documents in DB.
var express = require('express'); var mongoose = require('mongoose'); var app = express(); //connecting to the DB mongoose.connect('mongodb://sarthakdb:123ertyu@ds243345.mlab.com:43345/diary'); //creating a Schema var Schema = mongoose.Schema; var personSchema = new Schema({ firstname: String, lastname: String, phoneno: String, address: String }); //creating a model var Person = mongoose.model('Person', personSchema); //adding seed date var sarthak = Person({ firstname: "Sarthak", lastname: "Srivastava", phoneno: "9876543212", address: "DLF, Hyderabad" }) sarthak.save(function(err){ if(err) throw err; console.log('Person has been Saved!!!'); }); var john = Person({ firstname: "John", lastname:"Doe", phoneno: "8769877892", address: "California" }) john.save(function(err){ if(err) throw err; console.log('Person has been Saved!!!'); }); app.use('/', function (req, res, next) { console.log('Request Url:' + req.url); // get all the users Person.find({}, function(err, users) { if (err) throw err; // object of all the users console.log(users); }); next(); }); app.listen(3000);
Hence when you reun localhost:3000 in your browser it will create 2 documents in mlab DB and fetches them and prints all the documents in the command prompt
and updates the mlab console
Comments
Post a Comment