0

I have a collection of users with comments as an embedded document:

{
    id : "01",
    username : "john",
    comments : [
        {
          id : "001",
          body : "this is the comment",
          timestamp : 2012-04-23T18:25:43.511Z
        },
        {
          id : "002",
          body : "this is the 2nd comment",
          timestamp : 2015-03-22T18:25:43.511Z
        }
    ]
}

Now I would like to query for comments from a given timespan (let's say newer than 48 hours) with an associated username. In this case I would like to get the following JSON:

{
  username : "john",
  comments : [
      {
         id : "002",
         body : "this is the 2nd comment",
         timestamp : 2015-03-22T18:25:43.511Z
      }
  ]
}

How can I achieve it using MongoDB and mongoose?

CorrieSparrow
  • 521
  • 1
  • 6
  • 23
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Blakes Seven Mar 23 '16 at 00:08

1 Answers1

0

It should be something along these lines; I'm not so sure if did the timestamp calculation correctly, but I guess that's not that important for this question.

//connect to the database, define the Schema
mongoose = require('mongoose');
mongoose.connect(...database location...);

//I just assumed here that you named your collection "User", you can rename it to whatever you want
User = mongoose.model('User', username: String, comments: [{body: String, timestamp: Date}]);

//we need to define the variable where we'll hold our data in this scope.
var john;

Person.findOne({ 'username': 'John' }, function (err, person)
  {
    if (err) return handleError(err);
    john = {username: person.username, comments: person.comments.filter(function(el) {
        return (new Date) - comments.timestamp < 60 * 60 * 1000 * 48; 
        })};
});
  //variable john now contains your object
Bane Bojanić
  • 712
  • 1
  • 8
  • 20