简体   繁体   English

插入许多在 mongo DB 中不起作用的原因是什么?

[英]insert many don’t working in mongo DB why?

I am trying to insert many in mongoDB using mongoose's.it only save one collection only why Here is my code https://codesandbox.io/s/gallant-solomon-o91wp我正在尝试使用猫鼬在 mongoDB 中插入许多内容。它只保存one collection只是为什么这是我的代码https://codesandbox.io/s/gallant-solomon-o91wp

I save like that我就这样存

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);
  }
});

try to fetch data like that尝试获取这样的数据

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);
  }
});

showing only one document只显示一份文件

在此处输入图像描述

So, here as i suspected, there is one more index present in the collection you created ie blogposts .因此,正如我所怀疑的,您创建的集合中还有一个索引,即blogposts the index is id [key id name id_1 ].索引是id [key id name id_1 ]。 Here is your whole project, i have added in glitch.这是你的整个项目,我已经添加了故障。

Demo 演示

and here i also have added one api /indexes , this retrieves all indexes of the collection.在这里我还添加了一个 api /indexes ,这将检索集合的所有索引。 by default _id should be there, additional indexes are added after.默认情况下_id应该在那里,之后添加其他索引。 so here you can see id , which needs to be unique.所以在这里你可以看到id ,它必须是唯一的。

i have made few more changes to your code.我对您的代码做了一些更改。

The route /saveData now able to insert records.路由/saveData现在能够插入记录。 and it has the field called id which is unique.它有一个名为id的字段,它是唯一的。

but, the old route that is now at /saveData_old , which will give you error as there are no keys that represents this index key [ id ].但是,现在位于/saveData_old的旧路由,这会给您带来错误,因为没有表示此索引键 [ id ] 的键。 [also after inserting one, it will have id null and rest will fail, just causing duplicate ] [同样在插入一个后,它的id为 null 和 rest 将失败,只会导致重复]

now you can either use id key with unique values, or if you don't need you can also drop the index as well.现在您可以使用具有唯一值的id键,或者如果您不需要,您也可以删除索引。 you can find an answer here for how to drop index.您可以在此处找到有关如何删除索引的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM