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
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 i.e blogposts
. the index is id
[key id
name id_1
].
Here is your whole project, i have added in glitch.
and here i also have added one api /indexes
, this retrieves all indexes of the collection. by default _id
should be there, additional indexes are added after. so here you can see id
, which needs to be unique.
i have made few more changes to your code.
The route /saveData
now able to insert records. and it has the field called id
which is unique.
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
]. [also after inserting one, it will have id
null and rest will fail, just causing duplicate ]
now you can either use id
key with unique values, or if you don't need you can also drop the index as well. you can find an answer here for how to drop index.