1

I'm having this problem when removing an Object inside Array. I don't seems to understand what is the proper way of removing an item using $pull. Thanks in advance!

JSON data

"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"
    }
]

Code

  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);
  }
Koala
  • 352
  • 2
  • 7
  • 18
  • Have you read [the documentation for `$pull`](https://www.mongodb.com/docs/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents)? – robertklep Aug 07 '22 at 16:36
  • https://stackoverflow.com/questions/15641492/mongodb-remove-object-from-array – cmgchess Aug 07 '22 at 16:49
  • See my answer on: https://stackoverflow.com/questions/73204777/removing-an-element-from-the-array-in-mongodb-through-mongoose/73204854#73204854 – Alaindeseine Aug 07 '22 at 16:54

1 Answers1

0

I just solved my own question after a day realizing that a normal String is not equal to 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);
  }
Koala
  • 352
  • 2
  • 7
  • 18