One way to achieve this is through the findAndModify
method.
A convenient package exists that offers this feature, although personal implementation preferences might vary.
$ meteor add fongandrew:find-and-modify
Here is the GitHub repository for more information.
This package extends the functionality of the Mongo.Collection
prototype and ensures asynchronous operation via fibers on the server side.
If you pass true
as the second parameter, you can retrieve the raw output.
Check out this quick example involving an insert and an update:
> const Foo = new Mongo.Collection("foo");
> Foo.insert({foo: 1});
'6Mkpdjf3sXDZy6ioQ'
> Foo.findAndModify({query: {foo: 1}, update: {$set: {bar: 1}}, upsert: true}, true )
{ lastErrorObject: { updatedExisting: true, n: 1 },
value: { _id: '6Mkpdjf3sXDZy6ioQ', foo: 1 },
ok: 1 }
> Foo.findAndModify({query: {foo: 2}, update: {$set: {bar: 2}}, upsert: true}, true )
{ lastErrorObject: { updatedExisting: false, n: 1, upserted: 'y4eQzLWqCyBNr2WW9' },
value: null,
ok: 1 }
> Foo.findOne({foo: 2});
{ _id: 'y4eQzLWqCyBNr2WW9', foo: 2, bar: 2 }
>
To optimize the process, additional steps may be necessary, especially if consistent retrieval of the _id
is required.