Creating a Mongoose Model
suggest changeconst 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);
This assumes mongoose is already required and connected. MongoDB stores BSON; Mongoose schemas describe the shape of those documents. The variables at the top are only there to shorten the schema.
unique: true tells MongoDB to reject a second document with the same value. That is useful for fields such as an account email. required can be an array: the first element is the boolean, and the second is the message used when the value is missing.
ObjectId fields point at other documents. A comment's author can reference a user, for example. A plain string, such as a username, can be used instead.
Lastly, exporting the model for use with your API routes provides access to your schema.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents