skip to Main Content

I would like to delete an object from a JSON objects array. Here is the schema

qualifications: {
    Experience: [{
      title: String,
      companyName: String,
      location: String,
      years: Number
    }],
    Education:[ {
      school: String,
      years: Number,
    }],
    Licences: [String],
    Honnors: [String],
  }

For example how can I delete the object whose key is "school": "harvard university" ?

What i tried is

const user = await User.findOneAndUpdate(
      { _id: req.body.userid },
      {
        $pull: {
          qualifications: {
            Education: {
              school: "harvard university",
            }
          },
        },
      }
    );

But unfortunatelly it doesn’t get deleted from the database. what is wrong?

2

Answers


  1. qualifications is an object, thus you can’t use the $pull operator which requires an array field. Instead, you need the (.) dot notation to update the nested Education array: qualifications.Education.

    const user = await User.findOneAndUpdate(
    { _id: req.body.userid },
    {
      $pull: {
        "qualifications.Education": {
          school: "harvard university"
        }
      }
    })
    

    Demo @ Mongo Playground


    Updated

    From your error message, it seems qualifications is an array instead of an object. Your schema should be as below:

    qualifications: [{
        Experience: [{
          title: String,
          companyName: String,
          location: String,
          years: Number
        }],
        Education:[ {
          school: String,
          years: Number,
        }],
        Licences: [String],
        Honnors: [String],
      }]
    

    To remove the object from the nested arrays, the below query aims to remove all the objects with school: "harvard university" from the Education array, for the all objects in the qualifications array,

    const user = await User.findOneAndUpdate(
    { 
      _id: req.body.userid,
      "qualifications.Education.school": "harvard university"
    },
    {
      $pull: {
        "qualifications.$[].Education": {
          school: "harvard university"
        }
      }
    })
    

    Demo (remove object from nested arrays) @ Mongo Playground

    Login or Signup to reply.
  2. can you try:

    await User.update({ _id: req.body.userid },
              {
                "$pull": {
                  "qualifications.Education": {
                      "school": "harvard university",
                  },
                },
              });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search