簡體   English   中英

node.js - mongoose 中的嵌套數組 findOneandUpdate with arrayFilter

[英]node.js - nested array in mongoose findOneandUpdate with arrayFilter

我知道這是一個重復的問題。 但是我在更新嵌套的 arrays 時遇到了很多其他問題。 我可以手動編寫索引值,但顯然這在實際的 api 部署中沒有用。 那么arrayFilters可以用在長度為1的數組上嗎? 我應該重組前景 model,並將其還原為子文檔嗎? 任何幫助都會很棒。

控制台錯誤

MongoError:在路徑“resoStatus.representation.$[elem].document”中找不到標識符“elem”的數組過濾器

mongo中的文檔

:
Object_id:5f15a5fe911928412c858fb0
name:"State POA"
postedDate:2020-07-19T05:56:19.738+00:00
assigned:5efd0c3d75bb7122943e3a49

req.params.id: 5f15a5fe911928412c858fb0

不起作用的 function

router.put(
  "/:id/resoStatus/representation/:id",
  upload,
  auth,
  async (req, res) => {
    console.log(req.params.id);
    const prospect = await Prospect.findOneAndUpdate(
      { "_id": req.body.prospectId },
      {
        "$set": {
          "resoStatus.representation.$[elem].document": req.file.filename,
          "resoStatus.representation.$[elem].updatedDate": req.file.uploadDate,
          "resoStatus.representation.$[elem].id": req.body.id,
        },
        upsert: true,
        arrayFilters: [{ "elem._id": ObjectID(req.params.id) }],
      },
      (err) => {
        if (err) res.status(400).json(err);
      }
    );

    console.log(prospect.resoStatus.representation);
    res.status(200).json(prospect);
  }
);

確實有效的 function

router.put(
  "/:id/resoStatus/representation/:id",
  upload,
  auth,
  async (req, res) => {
    console.log(req.params.id);
    const prospect = await Prospect.findOneAndUpdate(
      { "_id": req.body.prospectId },
      {
        "$set": {
          "resoStatus.representation.0.document": req.file.filename,
          "resoStatus.representation.0.updatedDate": req.file.uploadDate,
          "resoStatus.representation.0.id": req.body.id,
        },
        upsert: true,
        arrayFilters: [{ "elem._id": ObjectID(req.params.id) }],
      },
      (err) => {
        if (err) res.status(400).json(err);
      }
    );

    console.log(prospect.resoStatus.representation);
    res.status(200).json(prospect);
  }
);

mongoose model

 representation: [
      {
        document: String,
        name: String,
        postedDate: Date,
        id: String,
        updatedDate: Date,
        endpoint: String,
        assigned: { type: mongoose.Schema.Types.ObjectId, ref: "user" },
      }]

您可以使用$ - 運算符更新與查詢文檔匹配的第一個元素:

"$set": {
          "resoStatus.representation.$.document": req.file.filename,
          "resoStatus.representation.$.updatedDate": req.file.uploadDate,
          "resoStatus.representation.$.id": req.body.id,
        }

如果需要更新匹配文檔的所有數組元素,可以使用全位置運算符

"$set": {
          "resoStatus.representation.$[].document": req.file.filename,
          "resoStatus.representation.$[].updatedDate": req.file.uploadDate,
          "resoStatus.representation.$[].id": req.body.id,
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM