2016-03-22 14 views
0

ich eine Sammlung von Benutzern mit Kommentaren als eingebettetes Dokument habe:MongoDB - eingebettetes Dokument holt neben einem Feld von seinem übergeordneten

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

Jetzt würde ich für Kommentare von einem gegebenen Zeitraum abfragen möchte (lassen Sie sich sagen neuer als 48 Stunden) mit einem zugehörigen Benutzernamen. In diesem Fall würde Ich mag die folgende JSON erhalten:

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

Wie ich es mit MongoDB erreichen kann und Mungo?

+0

Mögliches Duplikat [Retrieve nur das abgefragten Element in einem Objektarray in MongoDB Sammlung] (http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an- Objekt-Array-in-Mongodb-Sammlung) –

Antwort

0

Es sollte etwas in dieser Richtung sein; Ich bin mir nicht sicher, ob die Zeitstempelberechnung richtig war, aber ich denke, das ist für diese Frage nicht so wichtig.

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