User Registration with Mongoose models
In the previous blog we talked about how to connect MongoDb to Node.js server using Express.
For this article we will continue with allowing users to create an account.
The User Model
Let’s create a model for our users — each resource needs to have a Mongoose model with a schema.
- Create a new directory called ‘models’
- By convention, model files in Mongoose are singular and start with a capital letter. Create a file in
models
calledUser.js
- At the top of the file, import Mongoose. We will also need to require the Mongoose Schema:
Now, let’s think ahead to the information we need to require from a user and setup our schema:
As it showing we made some fields required and email unique so the user can not create multiple accounts with the same email.
Now it’s time to export our schema so we can user it later.
Let’s head back to our server route file and setup a route for user registration.
First let’s import User model schema to server route file
Now it’s time to create a route for user registration
The above code block will return an error if there is already a user registered with that email. Assuming that there is no user with that email, we can then save the user in the database.
Now it’s moment of truth to test out code… I’m going to test with Postman
- Make a
POST
request tohttp://localhost:3001/register
- Add a userName, email, and password to the request body
If you you followed all the instructions above you will get response back like this…