插入许多在 mongo 数据库中不起作用,为什么?

insert many don’t working in mongo DB why?

我正在尝试使用猫鼬在 mongoDB 中插入很多。它只保存 one collection 只是为什么 这是我的代码 https://codesandbox.io/s/gallant-solomon-o91wp

我就是这样存的

app.get("/saveData", async () => {
  try {
    const data = [
      {
        empid: "test123",
        date: "19-Jul-2019"
      },
      {
        empid: "test13",
        date: "18-Jul-2019"
      },

      {
        empid: "test13",
        date: "11-Jul-2019"
      }
    ];
    console.log("before save");
    let saveBlog = await BlogPostModel.collection.insertMany(data, {
      checkKeys: false
    }); //when fail its goes to catch
    console.log(saveBlog); //when success it print.
    console.log("saveBlog save");
  } catch (error) {
    console.log(error);
  }
});

尝试像那样获取数据

app.get("/filter", async (req, res) => {
  try {
    let filterBlog = await BlogPostModel.find({});
    //when fail its goes to catch
    console.log(filterBlog); //when success it print.
    res.send(filterBlog);
  } catch (error) {
    console.log(error);
  }
});

只显示一个文档

因此,正如我所怀疑的那样,您创建的集合中还有一个索引,即 blogposts。索引是 id [key id name id_1]。 这是你的整个项目,我添加了故障。

Demo

在这里我还添加了一个 api /indexes ,这会检索集合的所有索引。默认情况下 _id 应该在那里,之后添加额外的索引。所以在这里你可以看到 id,它需要是唯一的。

我对您的代码做了一些更改。

路由 /saveData 现在可以插入记录。它有一个名为 id 的字段,它是唯一的。

但是,现在位于 /saveData_old 的旧路由会给您带来错误,因为没有代表此索引键 [id] 的键。 [同样在插入一个之后,它将有 id null 并且其余的将失败,只是导致重复]

现在您可以使用具有唯一值的 id 键,或者如果不需要,您也可以删除索引。您可以找到有关如何删除索引的答案 here