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

142
Visualizações
Mongoose keep duplicate elements

I have a function that create guild entry for DiscordJS, but when the script start and also if the function is called multiple times, it create around 400 duplicate documents, it create by ID and the ID is unique, so it's not normal

My schema structure only have a ID type String and unique is true

client.createGuild = async guild => {
const exist = await Guild.findOne({ id: guild.id });

if(!exist) {
await Guild.create({ id: guild.id }); // new Guild().save() keep duplicate too
}

} 

It look like the if statement doesn't exist

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

0

const Schema = mongoose.Schema;

const FooSchema = new Schema({
   id: { type: String, index: true, unique: true }
});

const Foo = mongoose.model('Foo', FooSchema);

Foo.createIndexes();

If collection already exists. Create index manually to the collection via atlas or cmd.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can combine getData and createData functions to one. Here is the example:

const mongoose = require('mongoose');

async function getData(Guild, guild) {
    if (!mongoose.connection.readyState) await mongoose.connect('MONGO_URL'); // In case you haven't connect to database

    const data = await Guild.findOne({ id: guild.id }); // get data from database
    if (!data) {
        return new Guild({
            id: guild.id,
        }); // If no data exists for the guild, return new model
    }
    return data; // If the data already exists, return that
}

Now if you want to get data from mongodb you just call the function. It automatically create and save a new one if there is not.
Comment if you still have any problem or you have got what you need. Make sure to call the function with await or it won't return the 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