luisprooc/intermediate-node-course

Create User model

Opened this issue ยท 20 comments

Let's start by making a User model for mongodb using the mongoose library. This will be the template used to describe what each individual document will look like in our collection.

Find the "models" directory in the root of your project and open "User.js", then add this code to it:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});

module.exports= mongoose.model('User',UserSchema)

Looks like a JS object doesn't it? That is one of the cool things about MongoDB, it is easy to transfer data from the frontend to the backend. Think of this as a factory, or mold, that can create new User documents in a User collection.

Looking at the model above, which key (name, email, or password) needs to have unique values?

Leave a comment with your answer to continue

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

All Done

Sorry, that is not the answer we were looking for. The correct answer is: "email"

Leave a comment with the right answer to continue.๐Ÿ˜„

email

Correct! In this case, emails need to be unique. It makes sense to have at least one unique value, to avoid errors with authentication later on.

Here we are using route chaining as a shorthand for the "get", "put", and "delete" routes, since they all use the '/users/:id' endpoint. Remember that in 'users/:id' endpoint, id is a variable which can be accessed in the "req.params".

Now that we have a model, let's import it and connect to our database. Go to your server.js file and add these lines after all the libraries are imported.

const User=require('./models/User');
mongoose.connect('mongodb://localhost/userData')

The first line makes our User model available to use in express routes. The second line connects us to a local mongoDB database called: userData.

In the server.js file, you will notice some express routes set up for our users. It should look like this:

// CREATE
app.post('/users',(req,res)=>{
  // User.create()
})

app.route('/users/:id')
// READ
.get((req,res)=>{
  // User.findById()
})
// UPDATE
.put((req,res)=>{
  // User.findByIdAndUpdate()
})
// DELETE
.delete((req,res)=>{
  // User.findByIdAndDelete()
})

Inside each (req,res) callback function we use mongoose methods on our User model to Create, Read, Update, and Delete individual user documents in our users collection. The "POST" route is different than the others because mongoDB automatically creates an ID for each document when it is created. We are using route chaining as a shorthand for the "GET", "PUT", and "DELETE" routes, since they all use the /users/:id endpoint. The :id part of the endpoint is a variable which can be accessed in the "req.params".

In the commented out code in the routes above, what does User represent?

a. A MongoDB document
b. A MongoDB collection
c. A Mongoose Model
d. Data sent in the request body

Sorry, that is not the answer we were looking for. The correct answer is: "c"

Leave a comment with the right answer to continue.๐Ÿ˜„

Sorry, that is not the answer we were looking for. The correct answer is: "c"

Leave a comment with the right answer to continue.๐Ÿ˜„

You got it! Mongoose models come with a lot of useful methods (such as create) that make it easy to query for user documents in our user collection.

You can use the mongo shell to visualize your database and manipulate it through the command line. Before setting up our express routes with mongoose, try doing the following mongo shell commands:

  1. Open a new console and type in the mongo command.
  2. Select our database: use userData
  3. Insert a new user into a users collection:db.users.insertOne({name:"octocat",email:"octo@cat.com",password:"password"})
  4. Find all users: db.users.find()
  5. Delete all users: db.users.drop()

This is a good place for a commit. If a user was successfully saved to the database, push your code to GitHub to continue:

git add .
git commit -m"add user model and connect to db"
git push origin master