Skip to main content

Add a Controller

Define a route controller

Controller example

Here is a sample model that you can use as a start up

let model = require("../models/blogModel");
let AsyncError = require("../utils/catchAsync");

exports.updateData = AsyncError(async function (req, res, next) {
try {
let contents = await model.find({
name: req.body.name,
});

if (contents.length == 0) {
let newDoc = await model.create(req.body);
return res.status(200).json({ status: "success", data: newDoc });

return;
}

let content = contents[0];

let updated = await model.findOneAndUpdate({ _id: content._id }, req.body, {
new: true,
runvalidators: true,
});
res.status(200).json({ status: "success", data: updated });
} catch (error) {
logger.error(`An error occured ${error.message}`);
console.log("TC-5050", error.message);
res.status(500).json({
status: "failed",
message: error.message || "Internal server error",
});
}
});

exports.getData = AsyncError(async function name(req, res, next) {
try {
let data = await model.find();
res.status(200).json({
status: "success",
data,
});
} catch (error) {
logger.error(`An error occured ${error.message}`);
console.log("TC-5050", error.message);
res.status(500).json({
status: "failed",
message: error.message || "Internal server error",
});
}

Docs reference

info

A more detailed model with virtual methods and model references can be located at /docs/api-reference/Model.js from the project root

Controller development

Add your controller logs