MongoDB With Example
MongoDB With Example
MongoDB With Example
app.listen(8000);
console.log("Listening to PORT 8000");
mongoose.connect('mongodb://localhost:27017/TrainingProjectDb', {useNewUrlParser:
true},
(err) => {
if (!err) {
console.log('Successfully Established Connection with MongoDB')
}
else {
console.log('Failed to Establish Connection with MongoDB with Error: '+
err)
}
});
module.exports = mongoose;
module.exports = mongoose.model("Users", schema);
Now we have created the model, you can edit the fields according to
your needs.
Deleting a user
exports.delete = (req, res) => {
User.findByIdAndRemove(req.params.id)
.then((user) => {
if (!user) {
return res.status(404).send({
message: "User not found ",
});
}
res.send({ message: "User deleted successfully!" });
})
.catch((err) => {
return res.status(500).send({
message: "Could not delete user ",
});
});
};
Updating a user
exports.UpdateUser = (req, res) => {
if (!req.body.email || !req.body.password || !req.body.name) {
res.status(400).send({
message: "required fields cannot be empty",
});
}
User.findByIdAndUpdate(req.params.id, req.body, { new: true })
.then((user) => {
if (!user) {
return res.status(404).send({
message: "no user found",
});
}
res.status(200).send(user);
})
.catch((err) => {
return res.status(404).send({
message: "error while updating the post",
});
});
};
router.get("/", userControllr.findAll);
router.post("/", userControllr.create);
router.get("/:id", userControllr.findOne);
router.put("/:id", userControllr.UpdateUser);
router.delete("/:id", userControllr.delete);
module.exports = router;
Also after doing this do at these two line in the app.js file.
app.use("/users", require("./routes/user_route"));
Now hit run you will get your response will all the data and an id.
For the API's where we had to add an id in param.
you just had to add that id in with the link in such a way
http://localhost:8000/users/id
here id refers to the value of id.
You can test all of them in this way and play around to add more
validations to it or using different functions.