javascript findOneAndUpdate嵌套数组中的嵌套对象

von4xj4u  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(227)

我想更新MongoDb中另一个嵌套对象内部的嵌套对象,如下所示:

[
  {
    _id: ObjectId("637c648fb8fcfb2bc3071bb9"),
    consultant_name: "Sam letterman",
    consultantUsername: "sam",
    consultant_Password: "123",
    type: "consultant",
    clients: [
      {
        client_name: "john",
        client_Username: "mouh",
        client_Password: "123",
        type: "client",
        documents: [
          {
            name: "Acte de mariage",
            description: "copie conforme certifié du certificat de mariage",
            doc_upload: "",
            _id: ObjectId("637c648fb8fcfb2bc3071bbe")
          },
          {
            name: "Acte de de divorce",
            description: "because divorced",
            doc_upload: "",
            _id: ObjectId("637c648fb8fcfb2bc3071bbf")
          }
        ],
        
      },
      {
        _id: ObjectId("637c648fb8fcfb2bc3071bb9"),
        client_name: "narrakech",
        client_Username: "elsa",
        client_Password: "123",
        type: "client",
        documents: [
          {
            name: "Acte de mariage",
            description: "copie conforme certifié du certificat de mariage",
            doc_upload: "",
            _id: ObjectId("637c648fb8fcfb2bc3071bbe")
          },
          {
            name: "Acte de de divorce",
            description: "Parce que qu'on est shizo",
            doc_upload: "",
            _id: ObjectId("637c648fb8fcfb2bc3071bbf")
          }
        ]
      }
    ],
    createdAt: ISODate("2022-11-22T05:56:31.469Z"),
    updatedAt: ISODate("2022-11-27T03:40:31.835Z"),
    __v: 0
  }
]

更具体地说,我想做的是更新client_Username“艾尔莎”的“doc_upload”。

router.put('/:id', async (req, res) => {
    if (cond) {
        try {
            const updatedUser = await User.findOneAndUpdate({ 'clients._id': req.params.id }, {

                $set: { 'clients.$.client_name': 'narrakech' },

            }, { new: true });

            res.status(200).json(updatedUser);

        } catch (err) {
            res.status(500).json(err);
        }
    } else {
        res.status(401).json('You can update only you account.');
    }
})

这里我只能更新client_name(一个嵌套的对象),这是目前的情况。我想做的是更新她的一个特定文档(例如doc_upload部分),所有这一切背后的想法是访问第二个数组(documents),这是我现在不能用$符号做的。
在MongoDb中有什么方法可以做到这一点吗?
谢谢你

iq3niunx

iq3niunx1#

是的,有一种方法可以做到这一点,事实上有几种方法。
最简单的方法是使用array filters选项,如下所示:

db.collection.findOneAndUpdate({
  "clients._id": req.params.id
},
{
  $set: {
    "clients.$.client_name": "narrakech",
    "clients.$.documents.$[doc].doc_upload": "new doc upload"
  }
},
{
  arrayFilters: [
    {
      "doc._id": subDocumentId // this is the "query" to match the sub document in the documents array.
    }
  ]
})

Mongo Playground

相关问题