Jared Joke
Jared Joke

Reputation: 1356

How to avoid race conditions with mongoengine (make atomic changes to ListFields and DictFields)

I'm using mongoengine and seem to be running into some potential race condition incidents. As a simple example we have code that works something like this

def changeModel(newitemL, olditemD)
    model.randomList.append(newitemL)
    model.randomDict.pop(olditemD,None)
    model.save()

So if two users are trying to perform this action with different items then sometimes it will only show 1 users changes to the saved model. Is there a way I'm suppose to be changing ListFields and DictFields atomically to avoid this?

Upvotes: 2

Views: 519

Answers (1)

Ross
Ross

Reputation: 18111

Instead of doing a save, it would be better to do an update instead eg:

model.update(push__randomList=newitemL, pop__randomDict)

That way you will only impact those elements atomically.

Currently mongoengine is simple and naive when doing a save on list / dict fields eg:

model.randomList.append(newitemL)

# Converts to a set of the whole list:
model.update(set__randomList=model.randomList)

Upvotes: 2

Related Questions