Вот ваша схема
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema;
const userModel = new UserSchema({
sirName: String,
name: String,
email: String
});
module.exports = mongoose.model('user', userModel);
Ваши маршруты
const express = require('express');
const router = express.Router();
const user = require('../model/Users');
router.get('/users', (req, res, next)=>{
res.json({
'message': 'Fetch All User from Database'
});
});
//post request
router.post('/user', (req, res)=> {
const userData = new user({
sirName: req.body.sirName,
name : req.body.name,
email: req.body.email
})
userData.save()
.then(item =>{
res.send(item)
})
})
module.exports= router;
А вот ваш root файл
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const app = express();
const db = require('./setup/keys').my_url
const userRoutes = require('./routes/UserRoutes');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
mongoose
.connect(db, {useNewUrlParser:true, useUnifiedTopology:true})
.then(() => console.log('Connected'))
.catch(err => console.log(err));
app.use('/hi', userRoutes);
app.listen(port, () => console.log(`Server is running at ${port}`))
После отправки JSON Данные
Все данные сохраняются в базах данных
Работает отлично !!