Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!