diff --git a/spec/ParseAPI.spec.js b/spec/ParseAPI.spec.js index 084b7fe3..61efe8b3 100644 --- a/spec/ParseAPI.spec.js +++ b/spec/ParseAPI.spec.js @@ -5,6 +5,7 @@ var DatabaseAdapter = require('../src/DatabaseAdapter'); var request = require('request'); const Parse = require("parse/node"); +let Config = require('../src/Config'); describe('miscellaneous', function() { it('create a GameScore object', function(done) { @@ -1387,4 +1388,25 @@ describe('miscellaneous', function() { }) }); }); + + it('fail when create duplicate value in unique field', (done) => { + let obj = new Parse.Object('UniqueField'); + obj.set('unique', 'value'); + obj.save().then(() => { + expect(obj.id).not.toBeUndefined(); + let config = new Config('test'); + return config.database.adapter.adaptiveCollection('UniqueField') + }).then(collection => { + return collection._mongoCollection.createIndex({ 'unique': 1 }, { unique: true }) + }).then(() => { + let obj = new Parse.Object('UniqueField'); + obj.set('unique', 'value'); + return obj.save() + }).then(() => { + return Promise.reject(); + }, error => { + expect(error.code === Parse.Error.DUPLICATE_VALUE); + done(); + }); + }); }); diff --git a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js index d61df40c..81af4e97 100644 --- a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js +++ b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js @@ -166,7 +166,14 @@ export class MongoStorageAdapter { createObject(className, object, schemaController, parseFormatSchema) { const mongoObject = transform.parseObjectToMongoObjectForCreate(schemaController, className, object, parseFormatSchema); return this.adaptiveCollection(className) - .then(collection => collection.insertOne(mongoObject)); + .then(collection => collection.insertOne(mongoObject)) + .catch(error => { + if (error.code === 11000) { // Duplicate value + throw new Parse.Error(Parse.Error.DUPLICATE_VALUE, + 'A duplicate value for a field with unique values was provided'); + } + return Promise.reject(error); + }); } // Remove all objects that match the given parse query. Parse Query should be in Parse Format.