0

I am trying to update a data in mongodb using nodejs. I want the total data to be updated by +1 once a user creates a transaction. But I don't have any idea of it. Because there is no value coming back. like req.body, that I can pass in.

var UserSchema = new mongoose.Schema({
  total: { type: Number, default: 0 }
});

UserSchema.plugin(passortLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

app.post("/bitcoin", isLoggedIn, function(req, res) {
  client.createTransaction({ currency1: "USD", currency2: "BTC", amount: 500 },
    function(err, result) {
      if (err) {
        console.log(err);
      } else {
        User.findByIdAndUpdate(req.params.id, { total: +1 }, function(error,updated) {
          if (error) {
            console.log("error occured " + error);
            return res.redirect("/dashboard");
          } else {
            console.log("total updated" + updated);
          }
        });
        var coinPayment = result;
        res.redirect(coinPayment.status_url);
      }
    }
  );
});

It console.logs this below and it does not update any work around for this

total updated null
1
  • 1
    Seems that req.params.id is not in the collection. So the findByIdAndUpdate find nothing. Commented Mar 13, 2018 at 11:07

1 Answer 1

3

Try this, you have not declared id in params.

app.post('/bitcoin/:id',function(req, res){ /* Some stuff */})

Update Query

User.update({_id : req.params.id},{$inc: {total:1}})
Sign up to request clarification or add additional context in comments.

1 Comment

yeah thanks it is working correctly +1 to you. I had no knowledge of the $inc. :) @Rahul Sharma

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.