简体   繁体   中英

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' }));

使用第一种方法通过使用 $push 运算符,这会更有效,因为您让数据库完成所有工作,而不必将 Post 加载到内存中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM