无法通过mongoose中的id params删除文档?

时间:2017-11-07 05:33:35

标签: node.js mongodb mongoose

我不知道为什么我不能通过id删除文档,我在mongoose中使用findByIdAndRemove方法但不工作 这是我的控制器

const Todos = require('../model/todo');
const Users = require('../model/Users');
module.exports = {
    create(req,res,next){
        const newTodo = new Todos(req.body);
        newTodo.save()
        .then((todo)=>{
            res.send(todo);
        })
        .catch(next);
    },
    read(req,res,next){
        Promise.all([Todos.find({}),Todos.count()])
        .then((result,count) =>{
            res.send(result[0]);
            console.log(result[1]);
        })
        .catch(next);
    },
    searchTodos(req,res,next){
        const todoId = req.params.id;
        Todos.find({_id:todoId})
        .then(result=>{
            res.send(result);
            console.log("To do find: " + result.length);
        })
        .catch(next);
    },
    searchUsers(req,res,next){
        const userName = req.params.name;
        Users.find({name:userName})
        .then(result=>{
            res.send(result);
            console.log("User find count: " + result.length);
        })
        .catch(next);
    },
    removeManyTodos(req,res,next){
        const removeTodos = req.params.text;
        Todos.remove({text:removeTodos})
        .then(result=>{
            res.send(result);
        })
        .catch(next);
    },
    removeOneTodos(req,res,next){
        const TodoId = req.params.id;
        Todos.findByIdAndRemove({_id: new mongoose.mongo.ObjectID(req.params.id)})
        .then(result=>{
            res.send(result);
        })
        .catch(next);
    }

}

这是我的路线

const todoController = require('../controller/todoController');
module.exports = (app)=>{
    app.post('/api/todo',todoController.create);
    app.get('/api',todoController.read);
    app.get('/api/todo/:id',todoController.searchTodos);
    app.get('/api/users/:name',todoController.searchUsers);
    app.delete('/api/todo/:text',todoController.removeManyTodos);
    app.delete('/api/todo/:id',todoController.removeOneTodos);
}

我不知道我错了什么,为什么我不能删除它 removeMany无效,removeOneTodos也无效。如果我尝试使用{remove({_id:"5a012e4079879c2a995bea31"})这样的ID进行删除,那么它可以正常工作,但会按:localhost:3000/api/todo/5a012e4079879c2a995bea31之类的请求删除,但它无效...

1 个答案:

答案 0 :(得分:0)

Try this.
removeOneTodos.remove({
    "_id": req.params.id
   }, function(err, delTodo) {
})