2017-07-16 40 views
0
var userSchema=new mongoose.Schema({ 
username:String, 
password:String, 
email:String, 
tasks:[{ 
    task: String 
}] 
}); 

这是我的数据库schema.I想为要删除的任务创建删除路由。可以告诉我如何这样做。现在我可以获取任务ID。使用node.js删除mongodB中的数组的路由

这里是链接到我的C9项目https://ide.c9.io/akspan12/newprojectworkspace

+0

可能重复的[如何删除MongoDB中的数组元素?](https://stackoverflow.com/questions/16959099/how-to-remove-array-element-in-mongodb) –

回答

0
app.patch("/todo/:id",function(req,res){ 
    User 
    .findById(req.user.id, function(err, foundUser) { 
     if(err){ 
      req.flash("error",err.message); 
      console.log(err); 
      return res.redirect("back"); 
     } if(!foundUser) { 
       req.flash("error","User not found"); 
      return res.redirect("back"); 
     } else { 
      foundUser.update({$pull: {tasks: {_id: req.params.id}}}, function(err) { 
       if(err) { 
        req.flash("error",err.message); 
        console.log(err); 
        return res.redirect("back"); 
       } else { 
         req.flash("success","Task removed"); 
        return res.redirect("/todo"); 
       } 
      }); 
     } 
    }); 
}); 

这是我使用的删除路线。

0
var express = require('express'); 
    var router = express(); 

    //I will take static values you can give dynamic values by using req.body 
    router.post('/Delete_User_Task',function(req,res){ 
     var UserSchema = require('/path/to/Schema.js');//your schema model path 
     var username = 'akshansh123'; //assume it is present in db 
     //If you want to remove all task of this user and set one task as empty string your query and changes will be like below 
     var query = { 
      'username' :username 
     }; 
     var changes = { 
      $set:{ 
       'tasks':[{ 
        task:'' 
       }] 
      } 
     }; 

     //If you completely want to remove json array tasks from user document than your query and changes will be like below 
     var query = { 
      'username' :username 
     }; 
     var changes = { 
      $unset:{ 
       'tasks':'' 
      } 
     }; 

     //If you want to remove particular task suppose say sleeping from user document than your query and changes will be like below 
     var query = { 
      'username' :username 
     }; 
     var changes = { 
      $pull:{ 
       'tasks':{ 
        'task':'sleeping' 
       } 
      } 
     }; 
    //If you want to remove selected tasks suppose say sleeping,walking,drinking from user document than your query and changes will be like below 
     var query = { 
      'username' :username 
     }; 
     var changes = { 
      $pull:{ 
       'tasks':{ 
        'task':{ 
         $in:['sleeping','walking','drinking'] 
        } 
       } 
      } 
     }; 
     UserSchema.update(query,changes,function(err,Result){ 
      if(!err){ 
       res.send('Successfully Removed tasks'); 
      }else{ 
       res.send('something went wrong'); 
       console.log(err); 
      } 
     }) 

    }) 

希望这可以解决您的问题!

+0

我发现如何去做...但仍然感谢您的答复..我用补丁,而不是后 –

+0

你可以发布你的答案并关闭这个问题 –