Skip to content

Commit 8b32224

Browse files
authored
duplicate value on unique index error (parse-community#4560)
1 parent 530d111 commit 8b32224

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

spec/schemas.spec.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2387,4 +2387,28 @@ describe('schemas', () => {
23872387
});
23882388
});
23892389
});
2390+
2391+
it_exclude_dbs(['postgres'])('cannot update to duplicate value on unique index', (done) => {
2392+
const index = {
2393+
code: 1
2394+
};
2395+
const obj1 = new Parse.Object('UniqueIndexClass');
2396+
obj1.set('code', 1);
2397+
const obj2 = new Parse.Object('UniqueIndexClass');
2398+
obj2.set('code', 2);
2399+
const adapter = config.database.adapter;
2400+
adapter._adaptiveCollection('UniqueIndexClass').then(collection => {
2401+
return collection._ensureSparseUniqueIndexInBackground(index);
2402+
}).then(() => {
2403+
return obj1.save();
2404+
}).then(() => {
2405+
return obj2.save();
2406+
}).then(() => {
2407+
obj1.set('code', 2);
2408+
return obj1.save();
2409+
}).then(done.fail).catch((error) => {
2410+
expect(error.code).toEqual(Parse.Error.DUPLICATE_VALUE);
2411+
done();
2412+
});
2413+
});
23902414
});

src/Adapters/Storage/Mongo/MongoStorageAdapter.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,13 @@ export class MongoStorageAdapter implements StorageAdapter {
421421
const mongoWhere = transformWhere(className, query, schema);
422422
return this._adaptiveCollection(className)
423423
.then(collection => collection._mongoCollection.findAndModify(mongoWhere, [], mongoUpdate, { new: true }))
424-
.then(result => mongoObjectToParseObject(className, result.value, schema));
424+
.then(result => mongoObjectToParseObject(className, result.value, schema))
425+
.catch(error => {
426+
if (error.code === 11000) {
427+
throw new Parse.Error(Parse.Error.DUPLICATE_VALUE, 'A duplicate value for a field with unique values was provided');
428+
}
429+
throw error;
430+
});
425431
}
426432

427433
// Hopefully we can get rid of this. It's only used for config and hooks.

0 commit comments

Comments
 (0)