Introducing Models
We have our business logic stored in Controllers
and we create some data we want to store in the database or we get some data from the database. We need some classes for that and those are called Models
.
Introducing Models
So we have some users in our app and we want to store them in the database. We will create our model called User
and we will store it in new folder Models
that is in root folder of our project. As you see, Models
are just a normal classes with some specific properties for that model.
class User {
constructor(data) {
this.name = data.name ?? null;
this.age = data.age ?? null;
this.height = data.height ?? null;
this.weight = data.weight ?? null;
}
}
module.exports = User;
Improving our code
Now we can update our TestController.js
and use this model to store information about the user.
const User = require("../Models/User");
class TestController {
getTest({ req, res }) {
const user = new User({ name: "test", age: 100 });
return res.end(
JSON.stringify({
success: true,
message: "Works.",
data: user,
}),
);
}
postTest({ req, res }) {
return res.end(
JSON.stringify({
success: true,
message: "Works with data.",
}),
);
}
}
module.exports = TestController;
Now if you go to http://localhost:3000/test
you will get (something like) this in your browser:
{
"success": true,
"message": "Works.",
"data": {
"name": "test",
"age": 100,
"height": null,
"weight": null
}
}
You might have read or heard that Models
also have logic for running queries in DB(storing, deleting, etc.) but that is not correct. I am not talking about different patterns( such as Active Record
) but rather that whenever you create your own model(doesn’t matter if it extends some base model in a framework) YOUR model should not contain DB logic. You will learn very fast that such an approach(DB logic inside models) is not very good in the long run. Communication with DB is done in Repositories
(⏭️).
Folder structure
index.js
routes.js
Route.js
Ignitor.js
Models(folder)
- User.js
Controllers(folder)
- TestController.js
package.json
package-lock.json
.env
node_modules(folder)