fix(collection): improve duplicate key error reporting on insert
This commit is contained in:
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartdata',
|
||||
version: '7.1.5',
|
||||
version: '7.1.6',
|
||||
description: 'An advanced library for NoSQL data organization and manipulation using TypeScript with support for MongoDB, data validation, collections, and custom data types.'
|
||||
}
|
||||
|
||||
@@ -447,8 +447,22 @@ export class SmartdataCollection<T> {
|
||||
}
|
||||
|
||||
const saveableObject = await dbDocArg.createSavableObject() as any;
|
||||
const result = await this.mongoDbCollection.insertOne(saveableObject, { session: opts?.session });
|
||||
return result;
|
||||
try {
|
||||
const result = await this.mongoDbCollection.insertOne(saveableObject, { session: opts?.session });
|
||||
return result;
|
||||
} catch (err: any) {
|
||||
const isDuplicateKey = err?.code === 11000 || err?.codeName === 'DuplicateKey';
|
||||
if (isDuplicateKey && dbDocArg.uniqueIndexes && dbDocArg.uniqueIndexes.length > 0) {
|
||||
const identifiableObject = await dbDocArg.createIdentifiableObject();
|
||||
logger.log(
|
||||
'error',
|
||||
`Duplicate key conflict in "${this.collectionName}" on insert. ` +
|
||||
`A document with ${JSON.stringify(identifiableObject)} already exists. ` +
|
||||
`Use getInstance() to retrieve the existing document, or update it via save() on a db-retrieved instance.`
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user