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

105
Visualizações
JavaScript saving to mongodb

I have a loop that saves to mongodb. and sometimes its a bit to fast and I get duplicate error.

I iterate over a object and send each to a check function.


import checkExists from './checkExists';

const obj = [
 {name: "Sven", age: 18},
 {name: "Svenie", age: 18},
 {name: "Svenjo", age: 18},
 {name: "Sven", age: 18},
 {name: "Svenja", age: 18},
};

for(let i = 0; i < obj.length: i++){
 checkExists(obj[i]);
}

in checkExists I check in mongodb schema if there is a document with the name.

import SaveNewUser from './SaveNewUser';

export default async function checkExists(data){
 const {name} = data;
 const amount = await User.find({"name": name}).select("name").lean();

 if(amount.lenght > 0){
    return;
 } else {
    return SaveNewUser(data);
 };
};

Then in SaveNewUser I save to database

export default function SaveNewUser(data){
 const {name, age} = data;
 const userData = {
    "name": secondary,
    "age": age,
 };

 const saveNewUser = new User(userData);
 saveNewUser.save().then(()=>{
    return;
 }).catch((err)=>{
    console.log(err);
 });
};

so, in the start loop there is a double, and it gets send fast to the checkIfExists function. both do not exists yet and get send to the SaveNewUser, where the first will save and the second returns the double error.

this is just an simple example of my code, and there might be more double and I need to check and save data as fast as possible. Does anyone know a good way to make sure I don't get the error? I could add the checkIfExists function to the save function, but its the same problem.

I am thinking of making a file to save temp data and filter that, but it seems like a ugly solution. I need all functions to be separated in different js files for modular use.

-- Update --

The loop can be executed multiple times from another script with new user object.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Well, here are some weird stuff going on.

First of all i would rename obj to something different. Its confusing since its not an object its an array. Like userArray

You have the problem that you executing everything at once and not one by one checkExists returns an promise. You can await it

import checkExists from './checkExists';

const userArray = [
 {name: "Sven", age: 18},
 {name: "Svenie", age: 18},
 {name: "Svenjo", age: 18},
 {name: "Sven", age: 18},
 {name: "Svenja", age: 18},
};

()(async () => {
   for(let i = 0; i < obj.length: i++){
      await checkExists(obj[i]);
   }
})

And you have a typo at length

import SaveNewUser from './SaveNewUser';

export default async function checkExists(data){
 const {name} = data;
 const users = await User.find({"name": name}).select("name").lean();

 if(users.length > 0){
    return;
 } else {
    return SaveNewUser(data);
 };
};
about 4 years ago · Juan Pablo Isaza Relatório
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