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 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’);
- 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);
require comes from Node.js and is used for loading modules. In this case our friend, mongoose.
In mongoose, Schema is the base of everything, as it maps to a MongoDB collection.
We use require to include our User model definition from another file (it’s another Schema).
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.
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.