27
loading...
This website collects cookies to deliver better user experience
nodejs-api
and open it in any Code Editor (for this Tutorial I am using VS Code). Once you done open terminal ( You can either use VS Code terminal or external terminal ) and runnpm init -y
npm install express body-parser mongoose --save
server.js
in the root folder of the application and add the following code to itconst express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.json({"message": "Server is running :D"});
});
let PORT = 8080
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
node server.js
and go to http://localhost:8080
to access the route we just defined. and you should see{
message: "Server is running :D"
}
server.js
import mongoose, just like the code belowconst mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(YOUR_MONGODB_URL, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Error...', err);
process.exit();
});
server.js
should look like nowconst express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect(YOUR_MONGODB_URL,
{
useNewUrlParser: true,
}
)
.then(() => {
console.log("Successfully connected to the database");
})
.catch((err) => {
console.log("Could not connect to the database. Error...", err);
process.exit();
});
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.json({ message: "Server is running :D" });
});
let PORT = 8080;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
app
and inside of it create another folder named models
. app.model.js
and add the following code inside of itconst mongoose = require("mongoose");
const AppSchema = mongoose.Schema({
message: String,
});
module.exports = mongoose.model("App", AppSchema);
message
module.exports = (app) => {
const App = require("../controllers/app.controller.js");
app.post("/create", App.create);
app.get("/get-all", App.findAll);
app.get("/message/:messageId", App.findOne);
app.put("/message/:messageId", App.update);
app.delete("/message/:messageId", App.delete);
};
// ........
require('./app/routes/app.routes.js')(app);
// ........
const App = require("../model/app.model.js");
// Create and Save a new Message
exports.create = (req, res) => {
const message = new App({
message: req.body.message,
});
message
.save()
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Message.",
});
});
};
// Retrieve all messages from the database.
exports.findAll = (req, res) => {
App.find()
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving messages.",
});
});
};
// Find a single message with a messageId
exports.findOne = (req, res) => {
App.findById(req.params.messageId)
.then((data) => {
if (!data) {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
res.send(data);
})
.catch((err) => {
if (err.kind === "ObjectId") {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
return res.status(500).send({
message: "Error retrieving message with id " + req.params.messageId,
});
});
};
// Update a message identified by the messageId in the request
exports.update = (req, res) => {
App.findByIdAndUpdate(
req.params.messageId,
{
message: req.body.message,
},
{ new: true }
)
.then((data) => {
if (!data) {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
res.send(data);
})
.catch((err) => {
if (err.kind === "ObjectId") {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
return res.status(500).send({
message: "Error updating message with id " + req.params.messageId,
});
});
};
// Delete a message with the specified messageId in the request
exports.delete = (req, res) => {
App.findByIdAndRemove(req.params.messageId)
.then((data) => {
if (!data) {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
res.send({ message: "Message deleted successfully!" });
})
.catch((err) => {
if (err.kind === "ObjectId" || err.name === "NotFound") {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
return res.status(500).send({
message: "Could not delete message with id " + req.params.messageId,
});
});
};
messageId
messageId
in the requestmessageId
in the request