node.js-猫鼬中的嵌套数组findOneandUpdate与arrayFilter

时间:2020-07-20 14:27:02

标签: javascript node.js mongodb mongoose

我知道这是一个重复的问题。但是我遇到了同样的障碍,在更新嵌套数组方面似乎还有其他障碍。我能够手动编写索引值,但是显然这在实际的api部署中没有用。那么arrayFilters可以用于长度为1的数组吗?我应该重组前景模型,并将其还原为子文档吗?任何帮助都会很棒。

控制台错误

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

无效的功能

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

起作用的功能

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

猫鼬模型

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

1 个答案:

答案 0 :(得分:0)

您可以使用$-operator更新与查询文档匹配的第一个元素:

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

如果您需要更新匹配文档的所有数组元素,则可以使用all-positional operator

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