Reader small image

You're reading from  Mongoose for Application Development

Product typeBook
Published inAug 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781782168195
Edition1st Edition
Languages
Right arrow
Author (1)
Simon Holmes
Simon Holmes
author image
Simon Holmes

Simon Holmes started his journey as a web developer in the late 1990s. He built his first website for a project at university and soon saw what the industry had to offer when he promptly sold it! Following university, Simon worked his way through the ranks of design agency life, learning the skills of becoming a full-stack web developer. From server management and database design to building dynamic UIs from Photoshop files, it all fell under Simon's remit. Having witnessed first-hand the terrible JavaScript code so prevalent in the early 2000s, Simon is very much enjoying its resurgence as a powerful, structured language. Simon now works in SaaS, which is very heavy on the JavaScript.
Read more about Simon Holmes

Right arrow

Chapter 7. Interacting with Data – Updating

In the previous chapter, we've seen how to put data in and read it back out. It's time to see how to change the existing data. In this chapter, we will look at the three built-in static model methods that help us update in one command, and the instance method we can use to save a document following a find operation.

By the end of this chapter, you will have a good understanding of how to use the different approaches, and which one is appropriate to different scenarios. You will also have added the ability to make edits to the logged in user, update a project's information, and log the last time a user logged in.

Model helper methods


There are three static methods for updating data in a single go:

  • update(): This method updates matching documents in the database without returning them

  • findOneAndUpdate(): This method has the same approach as findOne that we looked at earlier, but writes the updates to the database before returning the found instance to the callback

  • findByIdAndUpdate(): This method is the same as findOneAndUpdate, but expects a unique ID instead of query object

Building the commands

Each of these methods can take the following four arguments:

  • conditions: These are the query conditions (or _id for findByIdAndUpdate) used to find documents to update

  • update: This is an object containing the fields and values to set

  • options: This is an object specifying options for this operation (see more details about this in just a moment)

  • callback: This is the function to run after a successful operation

The options differ depending on the call made. The update() method has one set of options you can set...

The three-step find-edit-save approach


This approach requires a few more steps and a bit more code than the helper methods but is more fully featured. The save() command accepts only one parameter, a callback function to run once the save has completed. This callback function can pass an error or return the saved object. Look at the following example:

// 1: FIND the record
User.findOne(
  {email : 'simon@theholmesoffice.com'},
  function(err, user) {
    if(!err){
      // 2: EDIT the record
      user.name = "Simon";
      // 3: SAVE the record
      user.save(function(err,user){
        console.log('User saved:', user);
      });
    }
  };
);

As you can see there is a bit more code required, and there's also an extra callback level. However, the code remains pretty simple to follow. To make it even easier, you can also define the callbacks as separate functions. We'll see this later.

CRUD – editing users and projects


While we haven't looked at validation yet, knowing the earlier "catch" will be very helpful while handling data interactions. We should bear it in mind when building our form handling actions, and use the correct methods wherever possible so that we don't have to rewrite them later.

Tracking user login

When a user logs in, we want to update the lastLogin date. We don't need any validation as we are setting the single field ourselves on the server, and we don't need the object returned from the database. We also know we are going to get the correct instance as our query object will be for the unique _id field, so we can use the update() method.

User login is currently handled by the doLogin function in routes/user.js. The section of the function that handles a successful login looks like the following:

req.session.user = { "name" : user.name, "email": user.email, "_id": user._id };
req.session.loggedIn = true;
console.log('Logged in user: ' + user);
res.redirect...

Summary


In this chapter, we have learned how to modify existing data using Mongoose. We have seen that there are some very simple methods we can use, but that this simplicity comes at a price. The price in this case is that defaults, validation, and middleware are not applied. We have also seen that we can use a more traditional three-step find-edit-save approach within Mongoose.

Following this theory we moved onto the practice and added to our MongoosePM project, making user and project information updatable, and updated the login script to record a timestamp of when the user logged in.

Coming up in the next chapter we will be learning about the last of the four CRUD cornerstones, deletion.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mongoose for Application Development
Published in: Aug 2013Publisher: PacktISBN-13: 9781782168195
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Simon Holmes

Simon Holmes started his journey as a web developer in the late 1990s. He built his first website for a project at university and soon saw what the industry had to offer when he promptly sold it! Following university, Simon worked his way through the ranks of design agency life, learning the skills of becoming a full-stack web developer. From server management and database design to building dynamic UIs from Photoshop files, it all fell under Simon's remit. Having witnessed first-hand the terrible JavaScript code so prevalent in the early 2000s, Simon is very much enjoying its resurgence as a powerful, structured language. Simon now works in SaaS, which is very heavy on the JavaScript.
Read more about Simon Holmes