0

well i've been working on a project and i want to delete an item inside an array in mongodb. here is my code

    return new Promise(async(resolve, reject) => {
    await categoryCollection.findOne({_id : ObjectID(this.category_id)}, async (err, cat) => {
        let x = this.cat_slug
        if(!err) {
            cat.sub_categories.forEach(function(s_cat) {
                if (s_cat.slug == x) {
                    // here i need to delete the array
                }
            })
        } else {
            reject(err)
        }
    })
})

}

and my mongodb collection as an exemple

{
"_id" : ObjectId("5e89db06a4c8d06b8b8784ae"),
"author" : ObjectId("5e89db06a4c8d06b8b8784ad"),
"name" : "Design",
"slug" : "design",
"sub_categories" : [ 
    {
        "author" : ObjectId("5e89e3914ebca9658b4bdae4"),
        "name" : "Games",
        "slug" : "games",
        "created_at" : "2020-4-5-6:55:38",
        "updated_at" : "2020-4-5-6:55:38"
    }, 
    {
        "author" : ObjectId("5e89e39c4ebca9658b4bdae5"),
        "name" : "Photoshop",
        "slug" : "photoshop",
        "created_at" : "2020-4-5-6:55:38",
        "updated_at" : "2020-4-5-6:55:38"
    }
],
"created_at" : "2020-4-5-5:56:55",
"updated_at" : "2020-4-5-5:56:55"

}

i wanna delete one item in the sub_categories array and that item am going to select it from my template engine (button) when i click on the delete button i should delete a specific item like the sub_categories[0] item i wanna delete it.

1 Answer 1

0

This can help you.

categoryCollection.update(
  { _id : ObjectID(this.category_id) },
  { $pull: 
    { 'sub_categories': 
      { "author": ObjectId("5e89e3914ebca9658b4bdae4") }
    }
  } 
)

It will work only if "author" is unique. If not. Add unique id for every "sub_categories".

Sign up to request clarification or add additional context in comments.

1 Comment

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.