Data modelling for 'followers count' in MongoDB app with RESTful API -


i have user entity has array of other user ids he/she following.

var userschema = {   following: { type: array } }; 

i have restful api, , when request user, application needs know how many followers user has.

the 2 options see are:

  • when user requested, count query such as: { following: { $in: [userid] } }
  • when user posted, check see whether user ids added or removed following array, , if were, use mongodb's $inc increment or decrement followerscount property on user document have been followed/unfollowed.

are other options? if not, best option? feel weird putting followerscount property in document itself, because suggests can updated application, when in fact dynamic count.

i have similar situation need restful api return number of articles associated website. count articles website on request, or store count property , update every time new article associated website created?

don't scared of storing more data think need in document. when started thinking along lines of mongo, rather rdms, freed thinking normalize everything. allowed me add more 'useful' information document, if wans't strictly necessary. transactions within document cheap, , cost of storage relatively cheap well. cost in finding information in document or collection expensive (processing wise) , possibly worth mitigating if can.

i understand concern having count in db 'the application can edit'. what? make sure application can't edit it, , if api open world, make sure can't edit either. usefulness of 'cached' count far outweighs fact potentially edited , fall out of sync. 1 of dangers of using nosql database: things end out of sync, since we're trusting application code keep data in order, rather relying on database.

consider this. if user gets removed, , count doesn't updated. make world of difference user? possibly not. while idea of background task check values (and worth having that), solution check integrity everytime user posts followers. in case have users anyway, , relatively inexpensive check count well. you're building in failsafe checks data integrity everytime message sent user. if user never sends, user doesn't care if count 100% accurate.

at end of day, if code tested, , defensive coding practices followed, shouldn't have consistency problems.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -