Home > Net >  How to update a field in a document in my monogoose model with Model.updateOne and $inc
How to update a field in a document in my monogoose model with Model.updateOne and $inc

Time:05-11

I'm making a digital currency app (for a closed community) and after making a transaction, I want to update the balance of the receiver in mongodb.

const create = (req, res) => {
    let transaction = new Transaction();
    transaction.sender = req.body.sender;
    transaction.receiver = req.body.receiver;
    transaction.amount = req.body.amount;
    transaction.save((err, doc) => {
        if(!err) {
            console.log(transaction.receiver);
            User.updateOne({username: transaction.receiver}, {$inc: {balance: 1}});

            res.json({
                "status": "success",
                "data": {
                    "transaction": doc
                }
            });
        } else {
            res.json({
                "status": "error",
                "message": "Could not make the transaction"
            });
        }
    })
}

When I test :

db.getCollection('users').updateOne({username: "aidenn"}, {$inc: {balance: 1}})

in RoboT3, the document updates. Why doesn't it work in my controller?

I test in Postman with:

{
    "sender": "Nicolas",
    "receiver": "aidenn",
    "amount": 1
}

CodePudding user response:

This should work: saveOne return a promise to you:

const create = (req, res) => {
  let transaction = new Transaction();
  transaction.sender = req.body.sender;
  transaction.receiver = req.body.receiver;
  transaction.amount = req.body.amount;
  transaction.save(async (err, doc) => {
    if(!err) {
        console.log(transaction.receiver);
        const updated = await User.updateOne({username: transaction.receiver}, {$inc: {balance: 1}});
       //verify the log
        console.log({updated})

        res.json({
            "status": "success",
            "data": {
                "transaction": doc
            }
        });
    } else {
        res.json({
            "status": "error",
            "message": "Could not make the transaction"
        });
    }
})

Here a readeable code this could be better using repository pattern and service:

const create = async (req, res) => {
  try {
    let transaction = new Transaction();
    transaction.sender = req.body.sender;
    transaction.receiver = req.body.receiver;
    transaction.amount = req.body.amount;
    const transactionSaved = await transaction.save();
    const updated = await User.updateOne(
      { username: transaction.receiver },
      { $inc: { balance: 1 } },
    );
    res.json({
      status: 'success',
      data: {
        transaction: transactionSaved,
      },
    });
  } catch (e) {
    res.json({
      status: 'error',
      message: 'Could not make the transaction',
    });
  }
};
  • Related