2013-01-21 107 views
1

訂購這是我的架構:發行日期與貓鼬

var userschema = new mongoose.Schema({ 

    user: String, 
    imagen: [{ 

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

      }], 
    follow: [String] 

}); 

這是代碼:

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

     usermodel.find({ _id: {$in: user.follow } }, function (err, images){ 

      console.log(images); 

      if (err) throw err; 

      res.render('home.ejs', { 

       user: user, 
       following: images 

      }); 

     }); 

}); 

架構中的後續數組包含_id S中的用戶的實際用戶正在關注。我試圖得到這樣的輸出:

{ _id: 50fd9c7b8e6a9d087d000006, 
    imagen: 
    [ { name: 'fff.png', 
     author: 'foo', 
     _id: 50fd9ca2bc9f163e7d000006, 
     date: Mon Jan 21 2013 20:53:06 GMT+0100 (CET) }, 
     { name: 'mmm.png', 
     author: 'foo', 
     _id: 50fda83a3214babc88000005, 
     date: Mon Jan 21 2013 21:41:34 GMT+0100 (CET) } ] }, 
{ _id: 50fd9d3ce20da1dd7d000006, 
     imagen: 
      [ { name: 'ddd.jpg', 
       author: 'faa', 
       _id: 50fda815915e068387000005, 
       date: Mon Jan 21 2013 21:42:57 GMT+0100 (CET) } ] } 

而我試圖獲得例如在這個類似的輸出,:

{ [ { name: 'fff.png', 
     author: 'foo', 
     _id: 50fd9ca2bc9f163e7d000006, 
     date: Mon Jan 21 2013 20:53:06 GMT+0100 (CET) }, 
     { name: 'ddd.png', 
     author: 'faa', 
     _id: 50fda815915e068387000005, 
     date: Mon Jan 21 2013 21:42:34 GMT+0100 (CET) }, 
     { name: 'mmm.png', 
     author: 'foo', 
     _id: 50fda83a3214babc88000005, 
     date: Mon Jan 21 2013 21:41:34 GMT+0100 (CET) } 
    ] } 

我想我要的是IMPOSIBLE,或者非常複雜,有沒有解決方案...?

謝謝先進!

+0

您可以使用'array1.concat( array2)''用一個循環將所有'imagen'數組連接在一起,然後按照日期對結果數組進行排序。我不認爲這種貓鼬分揀對此有幫助。希望我以正確的方式理解你的問題。 –

+0

但是,我在'for'loop內部執行的所有操作都是在循環結束時消失的,並且我在循環內部使用的數據做了一些操作,在循環外使用它,數據是相同的,for循環不會改變它。我猜是因爲我必須以異步方式對其進行編碼。 – MrMangado

回答

0

在這一行:

usermodel.find({ _id: {$in: user.follow } }, function (err, images){ 

images不好的名字,更好的名字是users甚至docs(你必須的的usermodel模式的文檔的陣中還有)。因此你的代碼中的images都是找到的文件。

我已經做了一個與您給出的相同架構的測試。這裏是我參加的所有user.imagen陣列,然後對它們進行排序的部分(當然是測試案例,但它的工作原理,希望這將導致你以正確的方式):

User.find {}, (err, users) -> 
    all_images = [] 
    # iterate users array to join all imagen arrays 
    for user in users 
    all_images.push user.imagen 
    # flatten nested arrays in all_images with underscore function 
    all_images = _.flatten all_images 
    # sort all_images the way you want (i.e. descending) 
    all_images.sort (a, b) -> b.date - a.date 
    # render page and see that it works 
    res.render 'test.html', {images: all_images}