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

            });

         });

});

Schema 中的 follow 数组包含_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) }
  ] }

我认为我想要的东西是不可能的,或者非常复杂,有什么解决方案可以解决这个问题......?

谢谢提前!

4

1 回答 1

0

在这一行:

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

images不是好名字,更好的名字是users甚至docs(你会在那里有一组用户模型模式的文档)。所以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}
于 2013-01-25T20:28:51.440 回答