Mongoose – Define a Model

To define a model, derive a custom schema from Mongoose’s Schema and compile the schema to a model.

How to recognize a Model

Let us consider that we are operating a bookstore and we need to develop a Node.js Application for maintaining the book store. Also we chose MongoDB as the database for storing data regarding books. The simplest item of transaction here is a book. Hence, we shall define a model called Book and transact objects of Book Model between Node.js and MongoDB. Mongoose helps us to abstract at Book level, during transactions with the database.

Derive a custom schema

Following is an example where we derive a custom Schema from Mongoose’s Schema.

</>
Copy
var BookSchema = mongoose.Schema({
  name: String,
  price: Number,
  quantity: Number
});

Compile Schema to Model

Once we derive a custom schema, we could compile it to a model.

Following is an example where we define a model named Book with the help of BookSchema.

</>
Copy
var Book = mongoose.model('Book', BookSchema, <collection_name>);

<collection_name> is the name of the collection you want the documents go to.

Initialize a Document

We may now use the model to initialize documents of the Model.

</>
Copy
var book1 = new Book({ name: 'Introduction to Mongoose', price: 10, quantity: 25 });

book1 is a Document of model Book.

Conclusion

In this Node.js Tutorial – Node.js Mongoose – Define a Model, we have learnt to use Schema to derive a custom schema and define a model by compiling the custom schema.