To communicate with our database, we need to define a data model for the contacts. Mongoose models serve as wrappers around schema definitions. A Mongoose schema defines the object structure, constraints, default values, and so on. Models are responsible for CRUD operations for an object with the underlying database.
To create a simple data model, let's create a Contact.js file in the models folder, and insert the following code into it:
// ./models/Contact.js
const Koa = require('koa');
const app = new Koa();
const mongoose = require('mongoose');
mongoose.connect(
'mongodb://localhost:27017/koa-contact',
{ useNewUrlParser: true }
);
const db = mongoose.connection;
db.on('error', error => {
throw new Error(`error connecting to db: ${error}`);
});
db.once('open', () => console.log('database connected'));
const port = process.env.PORT || 3000;
app.listen(port, () =>
console.log(`Server running on http://localhost:${port}`)
);
In the preceding code block, first, we require the mongoose dependency. The mongoose reference that is created here will be the same as the one that was returned when we initially connected to the database. This means that we do not need to create any other connections for interacting with our database.
Next, we define our schema by using the mongoose.Schema object. Our contact object will have the following properties:
- name: The name of a contact. This should be a string. This is a required value, and the schema validation will fail if a contact object without a name is persisted to the database.
- company: The company that a contact works at. This should be a string value.
- position: The position that a contact holds at a company. Also a string value.
- address: The contact's address. Also a string value.
- phoneNumber: The contact's phone number. This is also specified as a string value, to cater to special characters, such as a country code or parentheses.
- createdAt: The date that the document was created. This can be saved as a JavaScript date object. The default value is the current date.
- updatedAt: The date that the document was most recently updated. This can be saved as a JavaScript date object. The default value is the current date.
Finally, we will create the mongoose model and export it, so that it can be used elsewhere in our application.