MongoDB Connections in MEAN Stack



This article will  help you to get to know how to build up a database connection using mongodb. For this I am using Mongoose which is done by using object modelling.

First install mongoose using your command line and save it in the package.json file.
npm install mongoose --save

Now you can see that the dependency has been created in package.json file.Now require this into app.js file.Now you can create the database connection.Here before creating the connection, you should have run the mongo server. For that move on to the location where you have installed mongodb. If you haven't installed MongoDB refer this article






















Now move on to the bin folder and run the mongod server by typing mongod. as the output you can get the following.




Here port 27017 means the default port for mongo.


Creating the Connection

To create the connection create a new folder in your project called config in order to  reduce the complexity of the project.Then create a new file called database.js init.
Now export the file to access it.

module.exports = 
    "database":"mongodb://localhost:27017/my app" 
//my app is the database name
};
In app.js you have to require the database configuration file that we have created.
const config = require('./config/database');

Now you you add the mongoose connect part to app.js
const connection = mongoose.connect(config.database);//config.database is the database.js file path
Now write a if statement to check whether the connection has been established or not.
if(connection){
    console.log("Database created successfully");
}else{
    console.log("Something went wrong!");
}




Hope to see you soon with another article on MEAN stack

Comments

  1. very useful blog to learner so happy to be part in this blog. Thank you.
    MEAN stack Online Training

    ReplyDelete
  2. This article is very much helpful and i hope this will be an useful information for the needed one.Keep on updating these kinds of informative things.This idea is mind blowing. I think everyone should know such information like you have described on this post. Thank you for sharing this explanation.

    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore


    ReplyDelete

Post a Comment

Popular posts from this blog

Working with Buttons in Android Studio

Java Part 2 :How to Install Java