In this article, we will see how to connect MongoDB with Node.js using ORM called Mongoose. How to Connect Mongoose with Express Application
Implementing Twilio with Node.js
Mongoose is a ODM (Object Document Mapping) for the MongoDB database. Mongoose ease the process of Connecting and managing the MongoDB and Node.js
Mongoose is an ODM used to establish a connection with the MongoDB database. Above all, it provides schema structure for the database collection(In MySQL, it is called as Table)
First of all, install express and mongoose.
1npm init -yes2npm install mongoose express body-parser
Create a file name called app.js.
1const express = require("express")2const mongoose = require("mongoose")3const bodyParser = require("body-parser")45const app = express()67const PORT = 300089app.listen(PORT, () => {10 console.log(`app is listening to PORT ${PORT}`)11})
now start the server with the command node app.js and you should see some message in the console as app is listening to PORT 3000
Further, we need to connect MongoDB database using mongoose. Meanwhile, refer to this official documentation Mongoose
That is to say, connect mongoose to local MongoDB instance with db name as testdb
1mongoose.connect("mongodb://localhost:27017/testdb", {2 useNewUrlParser: "true",3})45mongoose.connection.on("error", err => {6 console.log("err", err)7})89mongoose.connection.on("connected", (err, res) => {10 console.log("mongoose is connected")11})
Final version of code should look like these. In conclusion, when we run the server with command node app.js . if we can see some message as mongoose is connected. then mongoose connection is established successfully.
1const express = require("express")2const mongoose = require("mongoose")3const bodyParser = require("body-parser")45const app = express()67mongoose.connect("mongodb://localhost:27017/testdb", {8 useNewUrlParser: "true",9})1011mongoose.connection.on("error", err => {12 console.log("err", err)13})1415mongoose.connection.on("connected", (err, res) => {16 console.log("mongoose is connected")17})1819const PORT = 30002021app.listen(PORT, () => {22 console.log(`app is listening to PORT ${PORT}`)23})
Mongoose handles everything as Schema. we need to design the schema for a Database Collection and we need to set the datatype that the collection is going to have.
For Example, if we are write a schema for an User. we can design it to have username, email and password
1const Mongoose = require("mongoose")23const userSchema = new Mongoose.Schema({4 username: {5 type: String,6 required: true,7 },8 email: {9 type: String,10 },11 password: {12 type: String,13 },14})1516Mongoose.model("User", userSchema)
No spam, ever. Unsubscribe anytime.