0

I have this query

router.delete('/:_id', async (req, res) => {
  const {_id} = req.params;
  const errors = [];
  console.log(_id);
  await Promise.all([
    // Pon.findOneAndDelete({_id}).catch((e) => {
    //   console.log(e);
    //   errors.push('Something went wrong. Pon was not deleted');
    // }),
    // ^^^^^^^^^ this part worked. Wanted to just test the other query
    User.findOneAndUpdate({_id: req.user._id}, {$pull: {pons: {_id}}}).catch((e) => {
      console.log(1, e);
      errors.push('Something went wrong. Pon reference was not deleted from user');
    }),
  ]);
  if (errors.length > 0) {
    console.log(2, errors);
    res.json({ok: false, errors});
  } else {
    res.json({ok: true});
  }
});

I am just trying to remove an element from user object. Here's the object

{
    "_id": {
        "$oid": "5ea2d8cffe35b93e84f7962b"
    },
    "pons": [
        {
            "$oid": "5ea98b181a2be04ec87aa710" // this is what I want to remove
        }
    ],
    "email": "[email protected]",
    "password": "$2a$12$VJ0MkcGUs42pikT42qLpyOb0Sd53j9LXH8dY9RdR/GcmUVzJoP8gi",
    "__v": 0
}

This query doesn't throw any errors, catch doesn't catch anything, so I don't know what I'm doing wrong. I tried just doing {pons: _id} instead of {pons: {_id}} but no luck.

The _id is correct. Checked with console.log.

What am I missing?

2
  • Are you sure req.user._id is also correct? Commented Apr 29, 2020 at 14:40
  • @TheeSritabtim just checked. Yes. it is correct Commented Apr 29, 2020 at 14:41

1 Answer 1

2

_id is just a String. If you want to match an ObjectId, you have to wrap it like this mongoose.Types.ObjectId(_id)

const ObjectId = mongoose.Types.ObjectId

User.findOneAndUpdate(
  { _id: ObjectId(req.user._id) },
  { $pull: { pons: ObjectId(_id) } }
)

Since you are querying by _id, you could also use User.findByIdAndUpdate() which will wrap req.user._id with ObjectId for you.

const ObjectId = mongoose.Types.ObjectId

User.findByIdAndUpdate(req.user._id, { $pull: { pons: ObjectId(_id) } })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.