如何使用 Model.updateOne 和 $inc 更新我的 monogose 模型中文档中的字段

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

我正在制作一个数字货币应用程序(用于封闭社区)并且在进行交易后,我想更新 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"
            });
        }
    })
}

当我测试时:

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

在 RoboT3 中,文档更新。为什么它在我的控制器中不起作用?

我在 Postman 中测试:

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

这应该有效:saveOne return 对你的承诺:

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

这是一个可读的代码,使用存储库模式和服务可能会更好:

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