FindOneAndDelete for subdocument

I’m using a Realm Function to update another document, but once it’s been updated, I want to delete the old one.

Right now I have in my user document an array called postsToApprove

Once it’s been dealt with (approve or disapprove), it updates another document with a trigger.

Afterward, I don’t want that subdocument in postsToApprove anymore.

I tried to do:

let postToDeleteQuery = {
          "_id": data._id,
          "postsToApprove._id": postsToApprove[i]._id
        };
        
        usersCollection.findOneAndDelete(postToDeleteQuery);

This works, except it deleted my user object instead of the subdocument.

How do I findOneAndDelete on a subdocument?

Thanks.

–Kurt

Hi @Kurt_Libby1,

I believe what you are looking for is a findOneAndUpdate with a $pull inside the Update clause:

As you need to remove array items.

usersCollection.findOneAndUpdate({"postsToApprove._id": postsToApprove[i]._id}{$pull : {"postsToApprove": {_id :postsToApprove[i]._id}}} )

Thanks
Pavel