Kevin.a
Kevin.a

Reputation: 4306

Dont add duplicate values MongoDB

I have the following Mongoose query :

let employeeData = [];
if (employees) {
  employeeData = employees.map((employee) => ({ name: employee.name }));
}

await Employee.insertMany(employeeData);

This works but adds a lot of duplicate values. I only want to insert unique values. How do i do this?

Upvotes: 0

Views: 37

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26410

  1. Set the name index as unique

    db.employees.createIndex( { "name": 1 }, { unique: true } )

  2. Use insertMany with the ordered:false option, which won't stop the insertion if there are duplicates

    await Employee.insertMany(employeeData, { ordered : false });

Upvotes: 1

Related Questions