How to create a POST api With Mongo DB and Node JS
badcaptain0001
Posted on January 24, 2024
first you have to build connection with you database for that will create db.js file you have to import this file in you main file named as index.js or server.js file you can see that in bottom code snippets
const mongoose = require("mongoose");
const express = require("express");
require("dotenv").config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.once("open", (_) => {
console.log("Database connected:", process.env.MONGODB_URI);
});
db.on("error", (err) => {
console.error("connection error:", err);
});
Create a usermodel.js file in your node js project
const moongoose = require("mongoose");
const userSchema = new moongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true }
phone: { type: Number, required: true }
//---- you can add multiple parameters over here
});
module.exports = moongoose.model("user", userSchema);
now will will create a route file where are going to access this schema and build api to store data on database
create a userroutes.js file
const express = require("express");
const router = express.Router();
const user= require("./usermodel.js");
//-------- api structure -------------------
router.post("/adduser", async (req, res) => {
const { name , email, phone} = req.body;
try {
const newUser= new user({
name,
email,
phone
});
const savedUser = await newUser.save();
res.status(200).json(savedUser);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router; //======>dont for get to add
you might already have this file named as server.js or index.js in your folder stucture where you are going to build you api structure
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
var cors = require("cors");
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());
require("./db");
const User = require("./userroutes.js");
app.use("/api", User);
const server = app.listen(process.env.PORT, () => {
console.log(`listening on port ${process.env.PORT}!`);
});
server;
so now you can create more apis
Happy Coding !
💖 💪 🙅 🚩
badcaptain0001
Posted on January 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.