This is responsible for handling our database interactions with registered users of our application. It will contain the following fields:
- fullName: This is a string value. The full name of the registered user. This is a required field, and should not be empty.
- email: This is also a string value. It is the email address of the registered user. Note that this value should be unique. We will make use of the mongoose-unique-validator plugin here to ensure the value is unique across all our app's users. This is a required field, and should not be empty.
- password: This is a hash of the user password. This should also be a string value. This is a required field, and should also not be empty.
- createdAt: The date the document was created. This can be saved as a JavaScript date object. The default value is the current date.
- updatedAt: The date the document was most recently updated. This can be saved as a JavaScript Date object. The default value is the current date.
To create the data model, let us create a User.js file in the ./models folder, and insert the following code into it:
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const schema = new mongoose.Schema({
fullName: {
type: String,
required: true
},
email: {
unique: true,
type: String,
required: true
},
password: {
type: String,
required: true
},
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
schema.plugin(uniqueValidator);
module.exports = mongoose.model('User', schema);
The mongoose reference created in the preceding code block when we require('mongoose') will be the same as the one that was returned when we initially connected to the database.
The mongoose-unique-validator plugin is used to add pre-save validation for unique fields within a Mongoose schema. After defining our schema, we export the model to be used in other places in our application.