2013-01-16 46 views
2

我提出了一個與此相關的問題,但我對使用貓鼬的聚合框架有了新的懷疑。例如,我有這樣的模式:帶貓鼬和數組的聚合框架

var userschema = new mongoose.Schema({ 

    user: String, 
    pass: String, 
    following: [String], 
    imagen: [{ 

       title: String, 
       date: { type: Date, default: Date.now }, 
       name: String, 
       author: String, 

      }], 


}); 

這是與聚合框架代碼:

app.get('/home', middleware.yeses, function (req, res){ 

usermodel.findOne({ user: req.session.user }, function (err, user){ 

model.aggregate([ 

     {$match: { _id : '50f5c7265838530000000006' }}, 
     {$unwind: '$imagen'},   
     {$sort: {'imagen.date': 1}} 

    ], function (err, imagenes){ 

     if (err) throw err; 

     console.log(imagenes); 

     res.send('foo'); 

    }); 
    }); 
    }); 

我想在控制檯中的所有images得到的,只是imagen畫質模式類似例如:

{ title: 'footitle', 
    name: 'foophoto.png', 
    date: Tue Jan 1 2013 22:32:12 GMT+0100 (CET), 
    author: 'foouser' } 

並獲取所有按日期排序的imagen模式。

以下用戶模式下的數組包含實際用戶所關注的用戶的_id。因此,在{$match: { _id : '50f5c7265838530000000006' }},的情況下,我只能看到我所關注用戶的圖像。問題是,執行此代碼時,我收到此[],我得到的圖像陣列爲空,所以代碼不起作用,因爲我遵循的用戶已上傳照片。

當我刪除這{$match: { _id : '50f5c7265838530000000006' }},我得到的所有用戶,他們的圖像,但我沒有得到只有imagen架構,我得到了整個用戶架構。

所以,我想要的是獲取我所遵循的用戶的所有圖像,按日期排序。有沒有解決方案?

謝謝先進!

回答

4

原因是您將_id字段作爲字符串傳遞,而不是ObjectID。試試這個:

var ObjectID = require("mongodb").ObjectID; 

// ... 

model.aggregate([ 

    {$match: { _id : ObjectID('50f5c7265838530000000006') }}, 

    // ...