0

我有一种在 mongoDB 数据库中插入任务的方法和一个显示所有任务的函数。

createTask(title, description) {

  if (!title) {
    return Promise.reject("you must provide a name for your Task");
  }

  if (!description) {
    return Promise.reject("You must provide description for your task");
  }

  return todo().then((todoItemsCollection) => {

    let newTask = {
      _id: uiud.v1(),
      title: title,
      description: description,
      completed: false,
      completedAt: null
    };

    return todoItemsCollection
      .insertOne(newTask)
      .then((newInsertInformation) => {
        return newInsertInformation.insertedId;
      })
      .then((newId) => {
        console.log("New task added");
        return this.getTask(newId);
      });
  });

},

getAllTasks() {
  return todo().then((todoItemsCollection) => {
    console.log("\nHere are All your Tasks");
    return todoItemsCollection.find().toArray((err, docs) => {
      docs.forEach((docs) => {
        console.log("\n");
        console.log(docs);
      });
    });
  });

}

我可以成功地在数据库中插入第一个任务,甚至能够从数据库中获取所有任务。但我无法在 app.js 中使用以下代码插入第二个任务“测试”。

let NewTask = todo.createTask("Ponder7 Dinosaurs", "Has Anyone Really Been Far Even as Decided to Use Even Go Want to do Look More Like?");

let taskAdded = NewTask.then((task) => {
    console.log(task);
});

let allTasks = taskAdded.then(() => {
    return todo.getAllTasks();
});

let NewTask2 = todo.createTask("Test", "Test");

let NewTask2 = todo.createTask("Test", "Test").catch((err) => {
    console.log(err);
}); 

当我试图捕捉错误时,它说

{ [MongoError: E11000 duplicate key error collection: lab3.todoItems index: _id_ dup key: { : "11477162-4844-4f5d-aae8-1afb8a560250" }]
  name: 'MongoError',
  message: 'E11000 duplicate key error collection: lab3.todoItems index: _id_ dup key: { : "11477162-4844-4f5d-aae8-1afb8a560250" }',
  driver: true,
  index: 0,
  code: 11000,
  errmsg: 'E11000 duplicate key error collection: lab3.todoItems index: _id_ dup key: { : "11477162-4844-4f5d-aae8-1afb8a560250" }' }

当我对 mongoDB ObjectID 做同样的事情时,第二个函数被调用,但在使用 node-uuid 模块时出现上述错误。

4

0 回答 0