Hello,
I'm trying to update a single object atomically as it could be written to from multiple users at - more or less - the same time. This should be done using collection.findOneAndUpdate. Is there any way I can use this within Parse, without having to use Mongo's NodeJS client?
you could use it via cloudCode, and maintain your own connection to mongoDB and run those operations atomically.
Note that many operations are already atomic (like increment, addUnique etc...)
Hey @flovilmart,
I already run my own connection from cloud code. My question was, whether there's a "parse" way to do it, or whether I have to implement it using the NodeJS Mongo client.
Also, regarding increment and other functions, I've tried them, and - unlike findOneAndUpdate - they don't force a write lock on the collection / document when I tried them.
same question here
I guess I'll go the mongo-driver-way.
On the mongodb, findOneAndUpdate of adapter uses findAndModify of mongoDB collection. (code)
findAndModify method is also atomically update. (docs)
So I use this way on cloud code :
Parse.Cloud.define('borrowBookFromLibrary', function(request, response) {
const { amount, bookId } = request.params;
const {
AppCache
} = require('parse-server/lib/cache'); // this refrenese only in cloud cloud
const app = AppCache.get(process.env.APP_ID);
if(!amount || amount <= 0 || ! bookId) { // some validation
response.error('invalid');
}
const schema = { // you don't have to write all specifics here, but have to have fields object.
fields: {
}
};
const query = {
objectId: bookId,
available: {
$gte: amount
}
};
const update = {
available: {
"__op": "Increment",
"amount": amount * -1
},
history: {
"__op": "Add",
"objects": [{
by: 'James',
requestDate: new Date()
}]
}
};
app.databaseController.adapter.findOneAndUpdate(
'BookLibrary',
schema,
query,
update
).then((result) => {
if (result) {
response.success({ success: true });
} else {
response.error({ error: true })
}
});
});
Most helpful comment
On the mongodb,
findOneAndUpdateof adapter usesfindAndModifyof mongoDB collection. (code)findAndModifymethod is also atomically update. (docs)So I use this way on cloud code :