How to delete an object from an array placed in userschema in mongodb using mongoose?

Viewed 40

UserSchema Completed tasks is an array from which i am trying to remove.

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var userSchema = new mongoose.Schema({
  username: String,
  password: String,
  completedtasks : [{task : String , time : String}] ,
});
userSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", userSchema);


Router code where i am trying to delete a completed task from an array.

:id is the id of the task stored in completedtasks array :uid is the id of user

My goal is to delete a task from completed task array.

But Mongoose documents didn't help that much.

I tried founduser.remove instead of update and it accidentally deleted my test user account which had a lot of data so i am not experimenting anymore.

router.put('/:id/deletectask/:user' , (req , res) =>{
  var tid = req.params.id ;
  var uid = req.params.user;
  User.findById(uid , function(err , founduser){

    if(err){console.log(err)}

    else{

    founduser.update( {} , 
      { $pull: {completedtasks : {_id : tid} }}
    ) ;
      res.redirect('/'+uid+'/ctl')
  }
  } )

})

2 Answers

You can do it like this way, in one query:

User.update({
    _id: uid
  }, {
    "$pull": {
      "completedtasks": {
        "_id": tid
      }
    }
  },
  (err, result) => {
    //do something here
  })

Thankyou so much Karl , sadly i had to learn this the hard-way and spend a lot of time , i completed the webdev bootcamp by Colt Steele and i am currently working on my first project .

Thanks for your help. <3.

Related