Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
Data loading fails when inserting a file of products in my Node server.js

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

Here is a sample of the data:

[
  {
     product_id: 667070,
     category_code: "FRT55",
     product_name: "Gala Apples",
     keywords: ['produce'],
  },
  {
     product_id: 667071,
     category_code: "FRT305",
     product_name: "Granny Smiths",
     keywords: ['produce'],
   },
];

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-project\node_modules\mongodb\lib\operations\insert.js:51:33
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda