DEV Community

Cover image for How to create a POST api With Mongo DB and Node JS
badcaptain0001
badcaptain0001

Posted on

How to create a POST api With Mongo DB and Node JS

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
});
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

so now you can create more apis

Happy Coding !

Top comments (3)

Collapse
 
louis_bertson_1124e9cdc59 profile image
Louis Bertson

Thank you for your plogpost:
Can you also publish about creating API with Total.js?

Collapse
 
rshrmcse profile image
badcaptain0001

yes

Collapse
 
louis_bertson_1124e9cdc59 profile image
Louis Bertson

THANK YOU