猫鼬findById返回null

时间:2019-10-26 14:44:42

标签: node.js mongodb express mongoose

我正在做一个待办事项列表应用程序。我使用以下功能将待办事项列表中的任务移至完成列表。但是,我用作url参数的“ columnId”方法和我使用的“ findById”方法返回null。您认为问题可能是什么?

public async Put(columnId: string, todo: ITodo): Promise<ITodo | null> {
    try {
        const editingTodo: ITodo | null = await Todo.findById(todo._id);
        if (editingTodo !== null) {
            const oldColumn: IColumn | null = await Column.findById(editingTodo.Column._id).exec();
            if (oldColumn !== null) {
                const todoIndexByOldColumn = oldColumn.Todos.indexOf(editingTodo._id);
                oldColumn.Todos.splice(todoIndexByOldColumn, 1);

                const newColumn: IColumn | null = await Column.findById(columnId).populate("Todos").exec();
                console.log(newColumn);
                if (newColumn !== null) {
                    newColumn.Todos.push(todo);
                    newColumn.save();
                    oldColumn.save();
                    editingTodo.save();
                }
            }
        }
        return editingTodo;
    } catch (error) {
        throw error;
    }
}

1 个答案:

答案 0 :(得分:0)

这是对猫鼬的待办事项清单的粗鲁操作。

// model todo 

 let todo = new schema({
    description: { type: String },
    heading: { type: String },
    title: { type: String },

 });

下面是具有所有操作逻辑的控制器。

// get All Todo List
let findAllTodoList = async (req, res, next ) => {
      let foundAllTodo = await todo.findAll({});
      res.send({ data: foundAllTodo });
 };

// get Specific Todo 
let findTodoById = async (req, res, next ) => {
      let todo_id = req.params.todo_id;
      let foundTodo = await todo.findById(todo_id);
      res.send({ data: foundTodo });
 };

// create Todo Element 
let createTodo = async (req, res, next ) => {
       let todo_obj =  {
          description: 'Here Add Element',
          heading: 'Adding',
          title: 'Add',
        };
      let foundTodo =  await todo.create(todo_obj);
      res.send({ data: 'success' });
 };

 // Destroy Todo Element 
let DeleteTodoById = async (req, res, next ) => {

      let todo_id = req.params.todo_id 
      let foundTodo =  await todo.remove({ _id:todo_id });
      res.send({ data: 'success' });
 };

module.exports = {
  findAllTodoList 
  findTodoById,
  createTodo,
  DeleteTodoById

};