I am using embedded array in mongoDB, Document looks same as below
{
"_id" : ObjectId("516f89b393307a0f73533863"),
"desc" : "LrOBVgWHHRyAxgYdKIwwgATcGTNBlz",
"comments" :[
{
"comment" : "superb",
"likeOrUnlike" : [
{"name":"kk",
"date":"2013/04/11",
"like":true
}
]
}
]
"date" : ISODate("2013-04-18T05:50:43.112Z"),
"title" : "OaTHxDDMoINSaZCHCSNpJLNQyrqXGZ"
}
I want to update the date and like field in the likeOrUnlike array inside the comments, Automic update is not possible in this scenario, so i thought of doing it manually by code(retrieving whole document and update),
In this case concurrency issue will occur
scenario : If two persons likes the same comment at same time.
So the solution is to lock the particular update function
var updateComments = function(id,data){
db.posts.findOne({"_id" :id},function(err,res){
// stuff
//mongo update
});
};
I can't post entire code.
My Question is
How to lock the function in node.js?
locking node.js function is good practice?
http://docs.mongodb.org/manual/reference/operator/positional/
use mongodb positional operator to update object inside a array
Locking should be a last resort. Use $push ( http://docs.mongodb.org/manual/reference/operator/push/ ) or another collection.