Mongoose configuration


Warning: This is a really old blog post. I am including it just for posterity, and in the interest of just keeping all my old writing from my “earlier” days.

A curious problem stumped me for a bit yesterday. Of course, once I brought it up with another Hacker Schooler, it was quickly resolved. This ‘skill’ of just asking people right away when an issue arises and not being embarassed to do so is something I am only beginning to warm up to and something that I wish I was more proactive at doing earlier on in my Hacker School career. The issue had to do with user.save. For some reason, when using req.user.save, I was unable to add to the existing userSchema. Although I couldn’t add or remove anything from the existing user, I could modify existing parameters. For example, I was able to change a “premium” parameter Boolean from true to false. I was able up update user’s listed email addresses as well using user.save.

In order to “add” parameters to the user, though, I needed to use a different command. Vito, another Hacker School (now called Recurse Center) peer, helped me find it via Mongoose’s documentation. There, it suggests the method of User.findOneAndUpdate(). Using this method, you introduce a parameter to search by (I used _id since it’s a unqiue identified in MongoDB) and then you feed it the element to modify, and then define a callback function.

User.findOneAndUpdate(
  {_id: user._id}, 
    user.toObject(), 
    function(err, updatedUser) {
      if (err) {
        throw err;
      } else {
        res.render('profile.ejs', {
          user : updatedUser,
          message: 'Project added successfully.'
        })
      }
    }
  ) 

Above is a snippet from my code that demonstrates this User.findOneAndUpdate() in action, with the callback function and render action defined within.