Basic Connected to MongoDB using Mongoose, node.js, and express.js
First of all, create a folder on your PC
mkdir anyFolderName
cd anyFolderName
Now initialization of some packages and dependencies.
npm init <initializer>
can be used to set up a new or existing npm package.
npm init -y
Now install some node packages like express, cors, dotenv, mongoose, MongoDB, and also install -g nodemon.
npm install express cors dotenv mongoose mongodb
npm install -g nodemon
Some dependencies will be installed in the package.json file
Now create some files like app.js, server.js, .env, and .gitignore
.gitignore file write ignore files like node_modules, .env, etc
node_modules
.env
Now write some line codes on app.js file
// app.js file
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose")
const app = express();
// middleware
app.use(cors());
app.use(express.json());
// root router
app.get("/", (req, res) => {
res.status(200).json({
status: "success",
message: "project is running...."
})
})
// not found router
app.all("*", (req, res) => {
res.status(400).json({
status: "failed",
message: "not found router"
})
})
module.exports = app;
Now write some line codes of the server.js file and connected Mongoose to the MonogoDB compass of a local database.
// server.js file
const app = require("./app");
require("dotenv").config()
const mongoose = require("mongoose");
// database connected
// database connect local of mongodb compass
mongoose.connect('mongodb://127.0.0.1:27017/databaseNameHere').then(() => {
console.log("successfully connected server")
}).catch((error) => {
console.log(error.message)
})
// server
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`listen port at : ${port}`)
The server.js file and connected Mongoose to the MonogoDB alter of an online database.
First of all, create a new cluster after already having a MongoDB account.
click + New Project
create a project and use any project name like (user-rendome-mongoose) here then click the next button
Now click Create Project button
Now create a database click Build a Database
Then select Free database of MongoDB and click Create
Now write a username and password must copy of userName and password then past of node pad or any here
then set the id address click like (ID Adress: 0.0.0.0/0) and Description write any message and click Add Entry button
Finally, click Finish and Close button
Click Go To Dashboses Button
now click connect button to find a MongoDB alter connection URL
Select Connect using MongoDB compass
2 Copy the connection string, then open MongoDB Compass URL:
Now edit server.js file with some line codes and it connected to online MongoDB alter database
const app = require("./app");
require("dotenv").config();
const mongoose = require("mongoose");
// database connected online
mongoose
.connect(
`mongodb+srv://userRandomeAdmin:${process.env.DATABASE_PASS}@cluster0.nmlzz1d.mongodb.net/databaseNameHere`
)
.then(() => {
console.log("successfully connected server");
})
.catch((error) => {
console.log(error.message);
});
// server
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`listen port at : ${port}`);
});
Now create a Mongoose schema and mode design
const mongoose = require("mongoose");
// mongoose schema deign
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: [true, "please proved a name"],
trim: true,
},
address: {
type: String,
trim: true,
},
},
{ timestamps: true }
);
// SCHEMA -> MODEL -> QUERY
// model design
const User = mongoose.model("User", userSchema);
// save a data of user example router
app.post("/user", async (req, res) => {
const userInfo = new User(req.body);
const result = await userInfo.save();
res.status(200).json({
status: "success",
data: result,
});
});
Now edit the package.json file and add 2-line codes of scripts.
"scripts": {
"start":"node server.js", // line 1
"start-dev":"nodemon server.js", // line 2
"test": "echo \"Error: no test specified\" && exit 1"
},
Now run the project using the command npm run start-dev of command PowerShell and see the output
Post data of Postman
Finally, store data from the MongoDB database