Al Capwned
Al Capwned

Reputation: 90

Mongoose Nested Queries - find and updating two fields in different documents

What Im trying to do is have one user send an amount to another user, Id like for the amount to be subtracted from the sender's balance, and added to the receiver's balance. The problem is that the receivers balance is updated and works, but the previous query to subtract the amount from the sender isn't working.

I understand there are no joins in mongoose (at least not in the classical sense), so Id need to query the user's balance first and then update it in another query. But surely there is a way to nest these queries? Im hoping I just have the syntax wrong.

user.js

const { Decimal128 } = require("mongodb");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },

  name: {
    type: String,
    required: true,
  },

  useraddress: {
    type: String,
    required: true,
  },

  userbalance: {
    type: Decimal128,
    required: true,
  }
});

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

server.js

app.post("/sendamount", function (req, res) {
  var amount = 100;
  var senderAddress = "Bob123";
  var receiverAddress = req.body.receiver;
  
  // Take amount from sender balance
  User.findOne({useraddress:senderAddress}, (err, sub) => {
    if (err) return handleError(err);
    var mybalance = parseFloat(sub.userbalance)
    console.log(mybalance)

    User.findOneAndUpdate(
      { useraddress: senderAddress },
      { userbalance: mybalance - amount }),
    
    // send to receiver balance
    User.findOne({useraddress:receiverAddress}, (err, sub2) => {
      if (err) return handleError(err);
      var receiverbalance = parseFloat(sub2.userbalance)
      console.log(receiverbalance)

      // add amount to receiver's balance
      User.findOneAndUpdate(
        { useraddress: receiverAddress },
        { userbalance: receiverbalance + amount }, 
        function (err, data) {
          if (err) res.send(err);
          res.send(data);
          console.log("found " + data)
          }
        )
      })
    })
  })

Would someone mind checking my code? Thanks

Upvotes: 0

Views: 279

Answers (1)

Taner Akhan
Taner Akhan

Reputation: 134

try to this subtrack process I added example field, you have this areas change

const asyncSubtrackProcess = async (id, amount) => await User.findOneAndUpdate({
            _id: mongoose.Types.ObjectId(id),
            userbalance: { $gt: 0 }
        },
        {
            $inc: {
                userbalance: - parseInt(amount)
            }
        });

const result = () => amounts.map(async item => await asyncSubtrackProcess(item.id, item.amount));
    result();

Upvotes: 1

Related Questions