Skip to main content

Philosophy

Models are objects that aim to manage a single document in a collection, it also provides multiple ways of creating, updating, deleting and fetching documents as utilities.

What is a model?​

A model basically is a class that represents a document in a collection, this helps us to manage the document in a more object oriented way.

Why not dealing with documents directly?​

Because when your application grows, you'd need to do more complex operations over documents, let's take an example, when we save a new model it automatically creates a new unique id for that document, and we can access that id using the id property, you would need to do this manually each time you create a new document, and this is just a simple example, there are many other things that you'd need to do manually if you don't use models.

Creating a model​

To create a model, you need to extend the Model class and define the collection property.

src/models/user.ts
import { Model } from "@mongez/monpulse";

export class User extends Model {
/**
* The collection name
*/
public static collection = "users";
}

This is the bare minimum to create a model, but we can do more, we'll see that as long as we go.

How to use a model?​

When creating a new model instance, you optionally pass an object of the data that will be saved (created).

src/app.ts
import { User } from "./models/user";

const user = new User({
name: "Hasan Zohdy",
email: "hassanzohdy@gmail.com",
isActive: true,
});

This only creates an instance of the model, but the data is not saved yet, now let's see how to save the data.

Saving a model instance​

To save a model instance, you need to call the save method.

src/app.ts
import { User } from "./models/user";

async function main() {
const user = new User({
name: "Hasan Zohdy",
email: "hassanzohdy@gmail.com",
isActive: true,
});

await user.save();
}

Once the model is successfully saved, a new id is assigned to the model instance.

Accessing Document ids​

By default, MongoDB generates _id for each document, and it's a unique identifier for each document in the collection, we can access the document id using the _id property.

src/app.ts
import { User } from "./models/user";

async function main() {
const user = new User({
name: "Hasan Zohdy",
email: "hassanzohdy@gmail.com",
isActive: true,
});

await user.save();

const _id = user._id;

console.log(_id); // ObjectId("5f9b2b3b3f3b9a0b3c3b9a0b")
}

This is good, but honestly i prefer ids as numbers, so we can use the good benefit of the auto generated id.

src/models/user.ts

import { User } from "./models/user";

async function main() {
const user = new User({
name: "Hasan Zohdy",
email: "hassanzohdy@gmail.com",
isActive: true,
});

await user.save();

const id = user.id;

console.log(id); // 1424151
}

Any generated id is randomly generated by default, later we'll see how to generate ids in a sequential way on all models or on a specific model.