node.js - What's the best way to store/query `last_read` in Mongo? -


i'm using mongodb (via mongoose/node), , i'm trying figure out best way store , query last_read date field. have collection of posts, , each time visitor views 1 of them, want store timestamp.

additionally, i'd query posts have been updated since current user's last_read timestamp.

this seems pretty standard, couldn't find much.

to me, simplest approach seems storing hash on post, keyed visitor id value being date. mongoose schema like:

{   title: string,   created: date,   modified: date,   last_read: {} // mixed } 

then upon loading post page, i'm running:

var update = {}; update.last_read[req.user.id] = new date(); posts.findbyidandupdate(req.params.id, update, cb); 

which works, , post doc looks like:

{   title: 'my new post',   created: 2015-04-01 06:25:53.094z,   modified: 2015-04-02 07:29:01.094z   last_read: {     123userid456: 2015-04-01 06:25:53.094z   } } 

but i'm not sure how query posts have been modified more current user's last_read time. need use aggregation pipeline?

i'm second-guessing storage approach altogether. @ first seems simplest option, using user id object keys feels wrong.

thanks help. :)

this not need type mixed for.

without altering aproach of saving data, should change schema this:

{    title: string,    created: date,    modified: date,    last_read: [{      _id: {        type: schema.types.objectid,        ref: 'user'      },      at: date    }]  }

using schema, can edit list of users read post this:

// add  post.last_read.push({    _id: user.id,    at: new date()  });    // find  var last_read = post.last_read.id(user.id);    // edit  last_read.at = new date();    // save  post.save(callback);

for more information on sub documents, please check mongoose documentation on topic.

but suggest using separate collection use case. because going have many posts read particular user , many users read particular post. big documents cause performance problems mongodb, more querying or editing collection.

{    user: {      type: schema.types.objectid,      ref: 'user'    },    post: {      type: schema.types.objectid,      ref: 'post'    },    last_read: date  }


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -