I am trying to load some product data into a Mongodb database before the Node server starts, I export the data loader in server.js. The failure is due to a duplicate key. First, I’m a newbie when it comes to Node. When I run the file on its own it loads the data without any issues. It only fails when I include in server.js
Here is the code for server.js
const express = require("express");
const app = express();
const http = require("http");
http.globalAgent = new http.Agent({
keepAlive: true
});
const connectDbi = require("./config/prod-config");
connectionDbi();
const router = require("./routes/productRoutes");
//Get the data loader here
const loader = require("./loader/dbLoader");
//Load the products here
loader.productsLoader();
app.use(express.json());
app.use("/api/v2/products", router);
app.listen(3000, () => console.log("Example app is listening on port 3000."));
Here is how the data is loaded
const fs = require("fs");
const Product = require("../models/Product");
const products = JSON.parse(
// Read products from a file
);
exports.productsLoader = () => {
Product.create(products)
.then(() => console.log("Products loaded"))
.catch((err) => console.log(err));
};
Unfortunately, the data starts getting loaded and then fails with a duplicate key after the first product is loaded. There is no other place except in server.js where this loader code is imported and used. How can a duplicate key arise from the loader? How can I prevent this from happening? Is there a better way to ensure this does not happen. I think this behavior may probably be because of the lifecycle process in Node, I’m quite new to Node.js
Here is the error:
Example app is listening on port 3000.
Connected to host localhost
MongoServerError: E11000 duplicate key error collection: products-db index: id_1 dup key: {
product_id: 667070 }
at c:mongo-projectnode_modulesmongodbliboperationsinsert.js:51:33