2

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')
  }
  } )

})

1 Answer 1

1

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

User.update({
    _id: uid
  }, {
    "$pull": {
      "completedtasks": {
        "_id": tid
      }
    }
  },
  (err, result) => {
    //do something here
  })
Sign up to request clarification or add additional context in comments.

Comments

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.