Home > Software engineering >  Mongoose keep duplicate elements
Mongoose keep duplicate elements

Time:03-19

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related