How To Connect Mongoose (MongoDB) With Express Application
In this tutorial, we will learn how to connect MongoDB with Node.js Using ORM called Mongoose. How to connect mongoose(MongoDB) with the express application.
MongoDB is an ODM (Object Document Mapping) for databases. MongoDB makes it easy to Connecting and managing node.js applications.
what is Mongoose?
Mongoose(MongoDB) is a document database with scalability and flexibility. Mongoose is an ODM used to establish a connection with the MongoDB database in node.js. it provides schema structure for the database collection. MySQL it is called as table.
First of all, install express and mongoose.
npm init -y
npm install mongoose express
Create a file name called index.js.
const express = require('express') const mongoose = require("mongoose") const app = express() const port = 3000 app.get('/', (req, res) => { res.send('Welcome to PhpCodingStuff.com We are learn node.js express mongodb') }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
Now start the server with the command node index.js and you should see some message in the console as the Example app listening at http://localhost:3000
Further, we need to connect the MongoDB database using mongoose. That is to say, connect mongoose to the local MongoDB instance with DB name as testdb. we learn node js connect to MongoDB.
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") })
The final version of the code should look like these. When we run the server with command node index.js. if we can see some message as a mongoose is connected. then mongoose connection is established successfully.
const express = require("express") const Mongoose = require("mongoose") const app = express() 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") }) const PORT = 3000 app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
Mongoose tutorial express handles everything as Schema. We need to design the schema for a Database Collection node.js express MongoDB and we need to set the data type that the collection is going to have.
For Example, if we are making a schema for a User. we can design it to have a username, email, and password.
const Mongoose = require("mongoose") const userSchema = new Mongoose.Schema({ username: { type: String, required: true, }, email: { type: String, required: true, }, password: { type: String, required: true, }, }) Mongoose.model("User", userSchema)
I hope it can help you...
Leave a Reply