繁体   English   中英

从 Mongoose 中的数组中删除 Object

[英]Remove Object from array in Mongoose

删除 Array 中的 Object 时遇到此问题。 我似乎不明白使用 $pull 删除项目的正确方法是什么。 提前致谢!

JSON 数据

"accountId": "62efd8c008f424af397b415d",
"links": [
    {
        "url": "www.github.com/iluvkohii",
        "title": "GitHub"
    },
    {
        "url": "www.github.com/iluvkohii",
        "title": "GitHub"
    },
    {
        "url": "www.github.com/iluvkohii",
        "title": "GitHub",
        "_id": "62efe1ee4675d0baa10bd219"
    },
    {
        "url": "www.github.com/iluvkohii",
        "title": "GitHub",
        "linkId": "62efe4e142099faeeb5999d0"
    }
]

代码

  try {
    const { accountId, _id } = req.body;
    return Profile.findOneAndUpdate(
      { accountId },
      { $pull: { links: { _id } } },
      { new: true, }
    )
      .then((value) => res.status(200).json(value))
      .catch((err) => res.status(400).json(err.errors));
  } catch (error) {
    console.error(error);
  }

一天后我刚刚解决了我自己的问题,意识到一个普通的字符串不等于 Mongoose ObjectId

  try {
    const { accountId, _id } = req.body;
    return Profile.findOneAndUpdate(
      { accountId },
      { $pull: { links: { id: mongoose.Types.ObjectId(_id) } } },
      { new: true },
    )
      .then((value) => res.status(200).json(value))
      .catch((err) => res.status(400).json(err.errors));
  } catch (error) {
    console.error(error);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM