reedy
reedy

Reputation: 33

how can I delete all the elements of a nested array within a mongo document using mongoose?

I am a complete MERN newbie please! I need to clear all the objects of an array in mongo document using mongoose. Most of the answers I found would just remove part of the array based on the condition given, but I want to clear the whole array so that I can repopulate it from user inputs.

Document :

 "_id": {
    "$oid": "5e3ff34551c1a940d23251d1"
},
"inter": {
    "significantEvents": []
},
"vigDataset": {
    "vigMovt": [
        {
            "Time": 2,
            "movt": 3
        },
        {
            "Time": 4,
            "movt": 5
        },
        {
            "Time": 6,
            "movt": 8
        },
        {
            "Time": 8,
            "movt": 8
        },
        {
            "Time": 9,
            "movt": 9
        },
        {
            "Time": 5,
            "movt": 5
        },
        {
            "Time": 10,
            "movt": 4
        },
        {
            "Time": 5,
            "movt": 6
        },
        {
            "Time": 9,
            "movt": 6
        },
        {
            "Time": 12,
            "movt": 3
        }
    ]

here is what i have tried from the express server without success:

   parRouter.route('/cleargraph/:parId')
.put((req, res, next) => {
  Par.findByIdAndUpdate(req.param.parId, {
    $pull: {"vigDataset.vigMovt"}
  })
  .then((par) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.json(par);
}, (err) => next(err))
.catch((err) => next(err));
})

and this is from the React end:

  handleClearGraph =(e)=> {
  Axios.put(baseUrl + `par/cleargraph/${this.props.par._id}`)
  .then(response => {
    console.log( response)
})

Upvotes: 1

Views: 159

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

If you wanted to pull all the elements of an array, then you can simply set that array value to [] :

parRouter.route('/cleargraph/:parId')
    .put((req, res, next) => {
        Par.findByIdAndUpdate(req.param.parId, {
            $set: { "vigDataset.vigMovt": []}
            // You can use {$unset : {'vigDataset.vigMovt': 1}} to remove field 'vigMovt' inside 'vigDataset'
        })
            .then((par) => {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'application/json');
                res.json(par);
            }, (err) => next(err))
            .catch((err) => next(err));
    })

Upvotes: 1

Related Questions