【问题标题】:How to update object in array of object of a document in mongoose?如何在猫鼬中更新文档对象数组中的对象?
【发布时间】:2020-07-31 02:52:20
【问题描述】:

我的用户架构是这样的

{
  _id:ObjectId("6e9465528a15ba6")
  name: 'XYZ',
  email: 'abc@gmail.com',
  transactions: [
    {
      _id:ObjectId("5e946557a5128a15ba6"),
      date: 2020-04-09T06:00:30.000Z,
      type: 'type1',
      category: 'category1',
      description: 'some desc',
    }
  ]
}

我想用特定的 id 更新一些交易字段。但没有发生。

我尝试了回答的解决方案 Mongoose, update values in array of objects这个问题。

可能是我的_id 是ObjectId 类型并且来自我的请求的id 是字符串? 那么我该如何解决这个问题呢?

我的代码是这样的,但仍然出现错误user.transactions._id is not function

app.post('/api/update', function (req, res) {
  const {
    id,
    email,
    date,
    type,
    category,
    description
  } = req.body;

  User.findOne({email}, function (err, user) {
    if (err) {
      console.error(err);
      res.status(500)
        .json({
          error: 'Internal error please try again'
        });
    } else if (!user) {
      res.status(401)
        .json({
          error: 'Incorrect email or password'
        });
    } else {
      const objectId = mongoose.Types.ObjectId(id);
      let transaction = user.transactions._id(objectId);
      transaction.date = date;
      transaction.type = type;
      transaction.category = category;
      transaction.description = description;

      user.save((err, data) => {
        if (err) return res.send(err);
        return res.sendStatus(200);
      });
    }
  });
});

【问题讨论】:

  • 我试过了,但似乎不起作用。请查看我有问题编辑的代码。
  • 请求中的id 是transactions._id 吗?或_id 用于文档?如果是针对transactions._id,那么即使给定电子邮件存在文档,对于给定id,什么id 不存在事务对象?
  • 它的交易ID。

标签: node.js mongodb express mongoose mongodb-query


【解决方案1】:

幸运的是我最近不得不做类似的事情,所以我建议你看看这个来自 Mongoose 文档的page,以防我错过了一些东西,但基本上你必须先找到文档,然后更新它的数组对象。

我会尝试这样的:

User.findOne({ _id: your_user_id }, (err, data) => {
    if (err) return console.log(err);

    if (data) {

      //Mongoose has a special method (id) for subdocuments
      var transaction = data.transactions.id(your_transaction_id);
      date: new Date(),
      type: 'type2',
      category: 'category2',
      description: 'whatever',

      //data.save() saves everything, document and subdocument
      data.save((err, data) => {
        if (err) return console.log(err);
        done(null, data);
      });

    }

【讨论】:

  • 你好,我也试过了,但似乎出错了。我用我的代码更新了问题。请看一下
猜你喜欢
  • 2022-08-18
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
相关资源
最近更新 更多