Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda