Mongoose helps us build a model for MongoDB in a easy way.

Create a folder called models in your root and add a new js file called post.js

That’s the code:

Now, this needs a little of explanations:

var mongoose = require(‘mongoose’);

require comes from Node.js and is used for loading modules. In this case our friend, mongoose.

var Schema = mongoose.Schema;

In mongoose, Schema is the base of everything, as it maps to a MongoDB collection.

var User = require(‘./user’);

We use require to include our User model definition from another file (it’s another Schema).

var schema = new Schema ( {

title : { type : String , required : true } ,

content : { type : String , required : true } ,

user : { type : Schema. Types . ObjectId , ref : 'User' }

} ) ;

Here we simply define the properties of our document. Two strings and a Schema.Types.ObjectId object.

This last line simply means: “Hey, our post has a user property which refers to an existing User in our database”.

So, our post is connected to one user.

module.exports = mongoose.model(‘Post’, schema);

The last thing we need to do is to create our model using the Schema just seen.