MongoDB - 从其父级获取嵌入式文档以及字段

时间:2016-03-22 22:52:36

标签: node.js mongodb mongoose

我有一组用户的评论作为嵌入式文档:

{
    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
        }
    ]
}

现在,我想查询给定时间跨度(假设超过48小时)的评论,并附带相关的用户名。在这种情况下,我想获得以下JSON:

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

如何使用MongoDB和mongoose实现它?

1 个答案:

答案 0 :(得分:0)

它应该是这些方面的东西;我不确定时间戳计算是否正确,但我认为这对于这个问题并不重要。

//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