Generate crud application in express with mongoose Schema
npm i express-crud-api-generator --save
yarn add express-crud-api-generator
It supports 2 parameters, both of which are required:
- app - express() instance
- options - with two required options:
- path - specify the base route. (For example: '/posts')
- modal - specify the mongoose schema modal.
If options.path = '/posts'
/posts/index
: get request for all data/posts/paginate/index
: get request for pagination data with optionspage=1&limit=10
(default page=1 and limit=10)/posts/create
: post request for particular data/posts/:id
: get data with particular id/posts/:id/edit'
: put and update data with particular id/posts/:id/delete
: delete request, delete data with particular id
Step 1: Create a new directory
Step 2: Initialize node app
npm init -y
Step 3: Add packages
npm i express body-parser cors mongoose dotenv express-crud-api-generator --save
or
yarn add express body-parser cors mongoose dotenv express-crud-api-generator
Step 4: Add .env file
MONGOURL=mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
Step 4: Add main file index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const mongoose = require('mongoose');
const DataModal = require('./modals/Data')
require('dotenv').config();
const generator = require('express-crud-api-generator')
app.use(bodyParser.json({limit: '50mb'}));
app.use(cors())
const db = process.env.MONGOURL;
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() =>{
console.log('Mongo Connection Successful')
app.enable('trust proxy');
})
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
//generate crud for the path /data
generator(app,{path:'/data',modal:DataModal})
generator(app,{path:'/antoherPath',modal:DataModal})
app.listen(port, () => console.log('Server started on port 5000'));
Step 5: Add modals like modals/Data.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const DataSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
});
module.exports = mongoose.model('data', DataSchema);
Step 6: Run the project node index.js