Giter Club home page Giter Club logo

mongodb-mongoose-web's Introduction

MongoDB-Mongoose-Web

I created this repo , just to save my Mongodb initial starter codes , so that it will be easy for me to access it whenever i feel that i forgot the syntax or want to refer to the code once.

Dependencies :

MongoDB atlas for Cloud Database.

folder structure : MVC structure

M=> Model
V=>Views
C=>Controller

1) Model=> contains the database model / Schema
2) Routes => Contains the Routes like GET,POST,PUT....
3) Controller => contains the logic of the project like create the moviePosts or how to get the posts.

Starter Code :

Code :

require('dotenv').config();
const express = require("express");
const app = express();

const mongoose = require('mongoose')
app.use(express.json());  //Middleware : to allow the json res.


// Database Connectivity:

mongoose.connect(process.env.MONGO_DB_URL,{
    useCreateIndex : true,
    useNewUrlParser : true,
    useUnifiedTopology: true,
}).then(()=>console.log("Database Connected Successfully "))
.catch((err)=>console.log(err))

app.listen(process.env.PORT || 5000 ,()=>{
    console.log("Server Connected Successfully.");
});

Models Folder :

I have created a file inside this folder called Mens.js where the Mens runners list are store. image

code :

const mongoose = require('mongoose')

const MenSchema = new mongoose.Schema({
    ranking : {
        type: Number,
        require: true, // this ranking field is REQUIRED ,else ERROR. 
        unique:true  // unique !
    },
    name : {
        type: String,
        require: true,
        trim:true  // means it will trim the SPACES
    },
    dob : {
        type: Date,
        require: true,
        trim:true 
    },
    country : {
        type: String,
        require: true,
        trim:true  
    },
    score : {
        type: Number,
        require: true,
        trim:true 
    },
    event : {
        type: String,
        default: "100m" // means byDefault set to 100 Meter if not provided the value.
    },
});

// we are creating a new Collection.
const MensRanking = new mongoose.model('MenRanking',MenSchema)

module.exports = MensRanking

image image

Now , Lets Configure the Router Folder

image

Code : Mens.js

const Router = require('express').Router();
const MensRankingModel = require('../Models/Mens');

Router.post('/', async(req,res)=>{
    try {
        const mensRecord = new MensRankingModel(req.body);
        const docResponse = await mensRecord.save();
        console.log(res.body);
        res.json(docResponse)
    } catch (error) {
        console.log(error)
        res.status(400).json(error)
    }
})

module.exports = Router;

So we have to make some changes to our Index.js file : so,

image

Code :

require('dotenv').config();
const express = require("express");
const app = express();
const mensRoute = require('./Routers/Mens.js')
app.use(express.json());  //Middleware : to allow the json res.


const mongoose = require('mongoose');
// Database Connectivity:

mongoose.connect(process.env.MONGO_DB_URL,{
    useNewUrlParser : true,
    useUnifiedTopology: true,
}).then(()=>console.log("Database Connected Successfully "))
.catch((err)=>console.log(err))

// using the Router from Routers folder.
app.use('/mens',mensRoute);
 
app.listen(3000 ,()=>{
    console.log("Server Connected Successfully.");
});

Testing the REST API using Postman tool :

image

IMPORTANT : image

(Note: the data should match the fields we have created in our schema. Fields can be also be 1 or 2 but should not more than the Defined Model schema.) image

RESPONSE :

image

MongoDB Atlas Database Response : image

Now Similarly , create other routes like GET PUT PATCH DELETE .. in the Router folder

^-^ Happy Coding ^-^

mongodb-mongoose-web's People

Contributors

yash-devop avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.