How to insert new document only if it doesn't already exist in MongoDB -


i have collection of users following schema:

{ _id:objectid("123...."), name:"user_name", field1:"field1 value", field2:"field2 value", etc... } 

the users looked user.name, must unique. when new user added, first perform search , if no such user found, add new user document collection. operations of searching user , adding new user, if not found, not atomic, it's possible, when multiple application servers connect db server, 2 add_user requests received @ same time same user name, resulting in no such user being found both add_user requests, in turn results 2 documents having same "user.name". in fact happened (due bug on client) single app server running nodejs , using async library.

i thinking of using findandmodify, doesn't work, since i'm not updating field (that exists or doesn't exist) of document exists , can use upsert, want insert new document if search criteria fails. can't make query not equal "user.name", since find other users.

first of all, should maintain unique index on name field of users collection. can specified in schema if using mongoose or using statement:

collection.ensureindex('name', {unique: true}, callback); 

this make sure name field remains unique , solve problem of concurrent requests have specified in question. not require searching when index set.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -