Skip to content

backend-master/express-mongodb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Simple Express With MongoDb

Install needed requirement using npm :

npm install

or using yarn :

yarn

Step By Step

  1. Install MongoDB and then start the service
  2. Connect our app with mongo :
const mongoose = require("mongoose");
const HOST = process.env.HOST;

mongoose.connect(HOST, {
  useNewUrlParser: true
});

HOST is usualy : mongodb://localhost/demodb

demodb will create automatically or will be used if this database is exist

  1. Define our models schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema({
  firstname: String,
  lastname: String,
  address: String,
  created_at: {
    type: Date,
    default: Date.now()
  },
  updated_at: {
    type: Date,
    default: Date.now()
  }
});

const User = mongoose.model("Users", userSchema);

module.exports = User;
  1. Make for models controller :
createUser: async (req, res) => {
    try {
      const { firstname, lastname, address } = req.body;
      const newData = { firstname, lastname, address };

      let user = new User(newData);

      const data = await user.save().then(result => {
        res.status(200).json({
          err: false,
          errMessage: null,
          data: user
        });
      });
    } catch (err) {
      res.status(500).json({
        err: true,
        errMessage: err,
        data: []
      });
    }
  }
  1. Add to your route :
Router.route("/")
  .post(userController.createUser)
  .get(userController.getAllUser);
  1. And then call your API, with starting your server :
yarn dev

Reference

  1. Mongoose Documentation
  2. MongoDB Documentation
  3. Install MongoDB

About

Learn How to connect mongodb with Express

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors