Skip to content

Commit f630a45

Browse files
authored
feat: Add $setOnInsert operator to Parse.Server.database.update (#8791)
1 parent fe02d3e commit f630a45

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

spec/MongoStorageAdapter.spec.js

+39
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,45 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
254254
expect(obj.get('foo').test.date[0] instanceof Date).toBeTrue();
255255
});
256256

257+
it('upserts with $setOnInsert', async () => {
258+
const uuid = require('uuid');
259+
const uuid1 = uuid.v4();
260+
const uuid2 = uuid.v4();
261+
const query = {
262+
x: 1,
263+
};
264+
const update = {
265+
objectId: {
266+
__op: 'SetOnInsert',
267+
amount: uuid1,
268+
},
269+
x: 1,
270+
count: {
271+
__op: 'Increment',
272+
amount: 1,
273+
},
274+
};
275+
await Parse.Server.database.update(
276+
'MyClass',
277+
query,
278+
update,
279+
{ upsert: true },
280+
);
281+
update.objectId.amount = uuid2;
282+
await Parse.Server.database.update(
283+
'MyClass',
284+
query,
285+
update,
286+
{ upsert: true },
287+
);
288+
const q = new Parse.Query('MyClass');
289+
const docs = await q.find();
290+
expect(docs.length).toBe(1);
291+
expect(docs[0].id).toBe(uuid1);
292+
expect(docs[0].get('x')).toBe(1);
293+
expect(docs[0].get('count')).toBe(2);
294+
});
295+
257296
it('handles updating a single object with array, object date', done => {
258297
const adapter = new MongoStorageAdapter({ uri: databaseURI });
259298

src/Adapters/Storage/Mongo/MongoTransform.js

+7
Original file line numberDiff line numberDiff line change
@@ -986,6 +986,13 @@ function transformUpdateOperator({ __op, amount, objects }, flatten) {
986986
return { __op: '$inc', arg: amount };
987987
}
988988

989+
case 'SetOnInsert':
990+
if (flatten) {
991+
return amount;
992+
} else {
993+
return { __op: '$setOnInsert', arg: amount };
994+
}
995+
989996
case 'Add':
990997
case 'AddUnique':
991998
if (!(objects instanceof Array)) {

src/Controllers/DatabaseController.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,9 @@ const flattenUpdateOperatorsForCreate = object => {
279279
}
280280
object[key] = object[key].amount;
281281
break;
282+
case 'SetOnInsert':
283+
object[key] = object[key].amount;
284+
break;
282285
case 'Add':
283286
if (!(object[key].objects instanceof Array)) {
284287
throw new Parse.Error(Parse.Error.INVALID_JSON, 'objects to add must be an array');
@@ -1817,7 +1820,7 @@ class DatabaseController {
18171820
keyUpdate &&
18181821
typeof keyUpdate === 'object' &&
18191822
keyUpdate.__op &&
1820-
['Add', 'AddUnique', 'Remove', 'Increment'].indexOf(keyUpdate.__op) > -1
1823+
['Add', 'AddUnique', 'Remove', 'Increment', 'SetOnInsert'].indexOf(keyUpdate.__op) > -1
18211824
) {
18221825
// only valid ops that produce an actionable result
18231826
// the op may have happened on a keypath

0 commit comments

Comments
 (0)