Install needed requirement using npm :
npm install
or using yarn :
yarn
- Install MongoDB and then start the service
- 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
- 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;
- 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: []
});
}
}
- Add to your route :
Router.route("/")
.post(userController.createUser)
.get(userController.getAllUser);
- And then call your API, with starting your server :
yarn dev