Skip to content

Unique fields

import { DriveDB, isDuplicateKeyError } from '@faeizfurqan/drivedb';
const db = new DriveDB(process.env.DRIVEDB_URL!).db();
const clients = db.collection('clients');
// Make email unique: every write is checked from now on.
await clients.createIndex({ email: 1 }, { unique: true });
try {
await clients.insertOne({ name: 'Copycat', email: 'mei@example.com' });
} catch (error) {
if (isDuplicateKeyError(error)) console.log('That email is already used:', error.details);
else throw error;
}
  • createIndex({ field: 1 }, { unique: true }) turns on Unique for that field. You can also tick Unique in the field’s settings in the app.
  • Existing duplicates make createIndex fail with DuplicateKey; clean them up first.
  • Inserts, updates, upserts and bulk writes that would create a duplicate fail with DuplicateKey, and nothing in that call is written. Empty values don’t count.
  • dropIndex('email_1') turns it off again. listIndexes() shows _id_ and the unique fields.

Other indexes (createIndex({ name: 1 })) are accepted so existing MongoDB code runs, but they change nothing: queries are always answered from memory.

Uniqueness is checked for writes made through the API. People editing in the app can still type a duplicate; after that, API writes that would add yet another copy of that value are refused, while other writes carry on.

Made by Faeiz Furqan