Create a model for MongoDB using Mongoose

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:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user');

var schema = new Schema({
    title: {type: String, required: true},
    content: {type: String, required: true},
    user: {type: Schema.Types.ObjectId, ref: 'User'}
});

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

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.

And it is done.
Now we can simply use Post to access the post collection in our Mongo database.

Just remember to include it where you need it.

var Post = require("../models/post"); // Your post.js filepath