Emma
Emma

Reputation: 317

Which method should be used to update a document in mongodb using mongoose?

I have two methods that updates the LIKES array in my post schema by inserting the user object in it. Both methods word fine but I want to know which approach is better and why. Also I am using mongoose in my application.

The LIKES keypair in my post schema:

likes:[{
    user:{
        type: Schema.Types.ObjectId,
        refPath:'onModel'
}        
}]

First Approach (By using $push operator)

Post.update({
    _id: req.params.postid,
    'likes.user': {
        $ne:
            authorizedData.jwt_payload.patient._id
    }
},
    { $push: { likes: { user: authorizedData.jwt_payload.patient._id } } })
    .then(post => res.json(post))
    .catch(err => res.json(err))

Second approach (By using mongoose save method)

Post.findById(req.params.postid)
    .then(post => {
      if (
        post.likes.filter(like => like.user.toString() === authorizedData.jwt_payload.patient._id)
          .length > 0
      ) {
        return res
          .status(400)
          .json({ alreadyliked: 'User already liked this post' });
      }

      // Add user id to likes array
      post.likes.unshift({ user: authorizedData.jwt_payload.patient._id });

      post.save().then(post => res.json(post));
    })
    .catch(err => res.status(404).json({ postnotfound: 'No post found' }));

Upvotes: 0

Views: 39

Answers (1)

Dan Starns
Dan Starns

Reputation: 3823

Go for the first approach By using $push operator, this is more efficient because you're letting the database do all the work & you don't have to load a Post into memory.

Upvotes: 1

Related Questions