Creating a Mongoose Model

suggest change
const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

const Article = new Schema({
  title: {
    type: String,
    unique: true,
    required: [true, 'Article must have title']
  },
  author: {
    type: ObjectId,
    ref: 'User'
  }
});

module.exports = mongoose.model('Article, Article);

Let’s dissect this. MongoDB and Mongoose use JSON(actually BSON, but that’s irrelevant here) as the data format. At the top, I’ve set a few variables to reduce typing.

I create a new Schema and assign it to a constant. It’s simple JSON, and each attribute is another Object with properties that help enforce a more consistent schema. Unique forces new instances being inserted in the database to, obviously, be unique. This is great for preventing a user creating multiple accounts on a service.

Required is another, declared as an array. The first element is the boolean value, and the second the error message should the value being inserted or updated fail to exist.

ObjectIds are used for relationships between Models. Examples might be ’Users have many Comments`. Other attributes can be used instead of ObjectId. Strings like a username is one example.

Lastly, exporting the model for use with your API routes provides access to your schema.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents