我正在做一个MERN项目,我需要更新Mongo数据库记录中的两个字段.

我有两个字段,一个是名为Wallets的对象数组,另一个是Transaction.

我正在从前端获取一个对象,其中包括金额,作为钱包进行交易的钱包的索引是Mongo中的对象array.

现在我需要从钱包中减go 交易额.如何操作我在node.js中编写了一个控制器,但它什么都不做.

我从前端收到的对象,如果..

transaction = { amount: '50', wallet: 0, type: 'expense', description: 'kmop' };

我的Node.js 控制器是...

module.exports.addTransaction = async (req, res) => {
  const transaction = req.body;
  const {wallet} = transaction;

  try {
      const walletName = `Wallets.${wallet}.amount`
      await UserModel.findOneAndUpdate(
        { email: email },
        {  $inc: { walletName : -transaction.amount}   ,
          $push: { transactions: { $each: [transaction], $position: 0 } } }
      );
      res.send({stat: true});
    } 
    else {
      console.log(data)
      res.send({ stat: false });
    }
  } catch (err) {
    console.log("err",err)
    res.send({ stat: false, err: err.message });
  }
};

我的芒果数据库唱片--

{"_id":{"$oid":"64a5a396ec152ab4f5e1c60c"},
"firstName":"Vinayak",
"lastName":"Pandey",
"email":"abc@123.com",
"password":"$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O",
"Wallets":[{"name":"paytm","amount":500},
           {"name":"hdfc","amount":5000},
           {"name":"test","amount":3020}]

Suppose i made a transaction from wallet namde paytm of rs 50 so i want that is the amount in object with name as paytm should be decreased by rs-50 so initially it was rs500 after the process it should became rs450....

推荐答案

在数组的一个元素上应用$inc运算符.我们应该使用dot notation在嵌入的文档或数组中指定<field>

百人组

$运算符标识要更新的数组中的元素,而不显式指定该元素在数组中的位置.

db.collection.update({
  email: "abc@123.com",
  "Wallets.name": "paytm"
},
{
  "$inc": {
    "Wallets.$.amount": -50
  }
})

mongoplayground

输入:

[
  {
    "_id": "64a5a396ec152ab4f5e1c60c",
    "firstName": "Vinayak",
    "lastName": "Pandey",
    "email": "abc@123.com",
    "password": "$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O",
    "Wallets": [
      {
        "name": "paytm",
        "amount": 500
      },
      {
        "name": "hdfc",
        "amount": 5000
      },
      {
        "name": "test",
        "amount": 3020
      }
    ]
  }
]

输出:

[
  {
    "Wallets": [
      {
        "amount": 450,
        "name": "paytm"
      },
      {
        "amount": 5000,
        "name": "hdfc"
      },
      {
        "amount": 3020,
        "name": "test"
      }
    ],
    "_id": "64a5a396ec152ab4f5e1c60c",
    "email": "abc@123.com",
    "firstName": "Vinayak",
    "lastName": "Pandey",
    "password": "$2b$10$dpAmLPa9imDKn3qeyhZ/hOwolO6NOYVwNvVgBc9PY8XZZ3n4WYh/O"
  }
]

UPDATE

使用特定的数组索引更新数组的元素:

const idx = 1;
db.users.updateOne(
    {
        email: 'abc@123.com'
    },
    {
        $inc: {
            [`Wallets.${idx}.amount`]: -50,
        },
    },
);

Node.js相关问答推荐

查询嵌套数组中的最后一个元素具有特定值的mongoDB集合中的文档

即使DDB键不存在, node Lambda也不会失败,并返回NULL作为结果

Mongoose查询-如何根据当前查找ID获取其他集合并将其插入到当前查找中?

如何在Mongoose中调用动态Collection ?

MongoDB的方面查询的Postgres类似功能

如果我加入另一个公会且我的​​机器人已在其中,欢迎消息发送错误

当API返回400状态代码时,使用Reactjs fetch获取错误消息

express 和 mongoose 的新密码不正确

每秒从套接字传来的数据有哪些存储方式?

如何从动态Typescript 文件加载模块

如何删除mongodb中嵌套数组中所有出现的数组元素

无服务器部署使用无服务器组合抛出`spawn serverless ENOENT`

为什么需要在 NodeJS 应用程序中创建服务器?

ISODate 未定义

所有的javascript回调都是异步的吗?如果不是,我怎么知道哪些是?

Nodejs 随机免费 tcp 端口

添加git信息到create-react-app

create-react-app,安装错误(找不到命令)

我可以有条件地将 where() 子句添加到我的 knex 查询吗?

expressjs app.VERB 调用中的 next() 和 next('route') 有什么区别?