ajayvarghese/intermediate-node-course

Create, Read, Update, and Delete

github-learning-lab opened this issue · 3 comments

CREATE: User.create

Let's start using this model to create some users.Insert the following code in the post route so it looks like this:

// CREATE
app.post('/users',(req,res)=>{
  User.create(
    {
      name:req.body.newData.name,
      email:req.body.newData.email,
      password:req.body.newData.password
    },
    (err,data)=>{
    if (err){
      res.json({success: false,message: err})
    } else if (!data){
      res.json({success: false,message: "Not Found"})
    } else {
      res.json({success: true,data: data})
    }
  })
})

When you want to make a new document in MongoDB, you can simply call the "create" method on your mongoose model. The first argument is an object containing the values for the new document (stored in req.body). The next argument is a callback function, which handles the response (res) from the database.

Testing

Ok let's test our code before we push it to GitHub. Start up Postman and set up a post request to: http://localhost:8000/users

Under the Headers tab, add this key/value pair:

Content-Type : application/json

Next, go to the body tab and select raw JSON, then paste this in the text under it:

{
  "newData":{
    "name":"Jim",
    "email":"jim@email.com",
    "password":"secretPassword"
  }
}

Send the post request, and see if you get a successful response. If our route worked, you should get JSON data back with the new user under "data". Notice that there is an "_id" key automatically created.

Leave a comment with the value of the _id key to continue

READ: User.findById

Great, your user has an id of Superseded by #8.. This is what we will use in place of :id, as we make the other requests. find the "READ" route in our server file, and replace it with this code:

// READ
.get((req,res)=>{
  User.findById(req.params.id,(err,data)=>{
    if (err){
      res.json({
        success: false,
        message: err
      })
    } else if (!data){
      res.json({
        success: false,
        message: "Not Found"
      })
    } else {
      res.json({
        success: true,
        data: data
      })
    }
  })
})

Testing

Let's find the document for the user we just created. Make a "get" request in postman to this url: http://localhost:8000/users/Superseded by #8.. This should return the document with the user's data.

Once you have this working, push your code to GitHub to continue.

UPDATE: User.findByIdAndUpdate

If you want to update a document in mongoDB, you can do it with the User.findByIdAndUpdate method. This takes three arguments (id, newData, callback). The id is still coming from "req.params", but newData is an object sent through the "req.body". Also, by default the update method will return the unmodified document. We can add an "options" argument before the callback ({new:true}) to make it return the modified document.

Replace the "UPDATE" route with this code:

// UPDATE
.put((req,res)=>{
  User.findByIdAndUpdate(
    req.params.id,
    {
      name:req.body.newData.name,
      email:req.body.newData.email,
      password:req.body.newData.password
    },
    {
      new:true
    },
    (err,data)=>{
      if (err){
        res.json({
          success: false,
          message: err
        })
      } else if (!data){
        res.json({
          success: false,
          message: "Not Found"
        })
      } else {
        res.json({
          success: true,
          data: data
        })
      }
    }
  )
})

Test this out by making a "PUT" request in Postman at the endpoint for our user. Update the password field by putting this json data in the request body:

{
  "newData":{
    "name":"Jim",
    "email":"jim@email.com",
    "password":"newPassword"
  }
}

If this worked, you should see the newly modified document as a response.

Push your code to GitHub for the next step.

Delete Data: findByIdAndDelete

To delete a document, you can use the User.findByIdAndDelete method, which takes an id and callback as arguments.

Replace the "delete" route with this:

// DELETE
.delete((req,res)=>{
  User.findByIdAndDelete(
    req.params.id,
    (err,data)=>{
      if (err){
        res.json({
          success: false,
          message: err
        })
      } else if (!data){
        res.json({
          success: false,
          message: "Not Found"
        })
      } else {
        res.json({
          success: true,
          data: data
        })
      }
    }
  )
})

To test this out, make a "delete" request in Postman to url we have been using.

You can test to make sure this worked by making a "get" request to the same url. It should say that the data could not be found.

Push your code to GitHub to complete this step.