title: Change voting function to only query from the database once (Mongoose)
body: <p>I wrote this code to manage voting on my server, however, I know that 3 queries is not good because it slows down the server. Is this possible to change?</p>
  <pre class="lang-js prettyprint-override"><code>app.post('/api/vote/:id', normalAuth, async (req, res) =&gt; {
      let vote = req.body.vote &gt; 0 ? 1 : -1;
  
      let currentPost = await Posts.findById(req.params.id).lean();
      let index = -1;
  
      for (let i = 0; i &lt; currentPost.voters.length; i++) {
          if (currentPost.voters[i].user === req.user._id) {
              index = i;
              break;
          }
      }
  
      if (index !== -1 &amp;&amp; currentPost.voters[index].vote == vote) {
          return res.send(currentPost);
      }
  
      let credit = vote === 1 ? 10 : -2;
  
      Posts.findByIdAndUpdate(req.params.id, {
          voters: {
              user: req.user._id,
              vote: vote
          },
          $inc: {
              votes: vote
          }
      }, {new: true},).lean().exec().then(item =&gt; {
          UserDetails.findByIdAndUpdate(req.user._id, {
              $inc: {
                  credit: credit
              }
          }).then(credit =&gt; {
              res.send(item)
          }).catch(err =&gt; {
              res.send(err)
          })
      });
  })
  </code></pre>
  <p>Is this possible? The first database call is to check if the user has already done the same vote, and if so, do nothing, this doubles as a way to get the vote. Then, I update the post to increment the votes and add the user as a voter to the voter array, and finally add the credit to the user.</p>