0

I'm trying to remove an embedded sub-document by the ObjectId. I have a parent event that has tags, the tags are their own document with their own schema that gets embedded into the parent event. When I run the code bellow the tag is not removed. If I change to remove the tag by it's name, using the same code the tag is removed. Not sure what I'm doing wrong here, from the documentation I've read, it seems like it should work..

This is the document:

{
"_id": "5ed67e2908fb3c03ac251ec6",
"eventStatus": "draft",
"title": "Testing tag removal",
"tags": [
    {
        "events": [
            "5ed67dddf909c05bf4cf72b9",
            "5ed67e2908fb3c03ac251ec6"
        ],
        "_id": "5ed67dddf909c05bf4cf72ba",
        "name": "Remove Tag",
        "slug": "remove",
        "__v": 0
    }
]

}

Here's the code to remove:

app.put(
    "/api/remove/event/field/:id/:name/:value",
    requireLogin,
    async (req, res) => {
        const result = await Events.findByIdAndUpdate(
            req.params.id,
            { $pull: { tags: { _id: req.params.value } } },
            { new: true }
        );
        console.log(result)
        res.send(result);
    }
);

The console.log shows that the tag is not removed.

My Schema for this looks like and Tags references it's own Schema:

const eventsSchema = new Schema({
_createdBy: { type: Schema.Types.ObjectId, ref: "Users" },
title: String,
createdDate: Date,
modifiedDate: Date,
eventStatus: String,
category: String,
tags: [tagSchema],});

Tags Schema:

const tagSchema = new Schema({
name: String,
slug: String,
events: [
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Events",
    },
],});

Appreciate any help or guiadance.

Mike G
  • 15
  • 4

0 Answers0