Node js Connect to MongoDB using Mongoose Tutorial

1. Install Mongoose

First, you need to install Mongoose in your project. You can do this by running the following command in your terminal:

npm install mongoose

2. Connect to MongoDB

Once you have installed Mongoose, you can connect to your MongoDB database by creating a Mongoose connection. To do this, you need to create a new Mongoose instance and pass in the connection string for your MongoDB database.

const mongoose = require(‘mongoose’);

mongoose.connect(‘mongodb://localhost/my_database’, {
useNewUrlParser: true,
useUnifiedTopology: true
});

3. Create a Schema

Once you have connected to your MongoDB database, you need to create a Mongoose Schema. A Schema is a blueprint for your data that defines the shape of the documents in your collection.

const userSchema = new mongoose.Schema({
name: String,
age: Number
});

4. Create a Model

Once you have created a Schema, you can use it to create a Mongoose Model. A Model is a class that allows you to create documents in your collection.

const User = mongoose.model(‘User’, userSchema);

5. Create a Document

Once you have created a Model, you can use it to create documents in your collection.

const user = new User({
name: ‘John Doe’,
age: 25
});

user.save();

6. Query the Database

Once you have created documents in your collection, you can query the database to retrieve them.

User.find({name: ‘John Doe’}, (err, users) => {
if (err) {
console.log(err);
} else {
console.log(users);
}
});
[ad_1]

Connect to mongodb using mongoose in node js express tutorial, you will learn how to connect mongoose with node js express application.

MongoDB is a document database built on a scale-out architecture that has become popular with developers of all kinds who are building scalable applications using agile methodologies. MongoDB was built for people who are building internet and business applications who need to evolve quickly and scale elegantly.

How to Connect Mongoose with Node js Express Application

  • Step 1 – Create Node JS App
  • Step 2 – Install Express-Validator and Body Parser Module
  • Step 3 – Create Server.js File
  • Step 4 – Connect App to MongoDB
  • Step 5 – Start App Server

Step 1 – Create Node JS App

Create Node js express app; So, execute the following command on terminal:

mkdir my-app
cd my-app
npm init -yes

Step 2 – Install Mongoose and Body Parser Module

Install mongoose s and body-parser modules into your node js express application by executing the following command on command prompt:

npm install mongoose express body-parser

  • body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.

Step 3 – Create Server.js File

Create Server.js and import above installed modules in it. So visit your app root directory and create Server.js and validate fields; as following:

const express = require("express")
const mongoose = require("mongoose")
const bodyParser = require("body-parser")
const app = express()
const PORT = 3000
app.listen(PORT, () => {
  console.log(`app is listening to PORT ${PORT}`)
})

Step 4 – Connect App to MongoDB

Connect mongoose to local MongoDB instance with db name as testdb; so add the following code into server.js file:

mongoose.connect("mongodb://localhost:27017/testdb", {
  useNewUrlParser: "true",
})
mongoose.connection.on("error", err => {
  console.log("err", err)
})
mongoose.connection.on("connected", (err, res) => {
  console.log("mongoose is connected")
})

Step 5 – Start App Server

Open your command prompt and execute the following command to run node js express file upload application:

//run the below command

node sever.js

Conclusion

Connect to mongodb using mongoose in node js express tutorial, you have learn how to connect mongodb using mongoose with node js express application.

Recommended Node Js Tutorial

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00