2013-02-17 28 views
0

如此充满,我有两个猫鼬型号:通过数组的长度排序,如果它没有在模型

User: { 
    name: String, 
    .......... 
    locations: [] 
} 

Location: { 
    title: String, 
    ............. 
    owner: { 
     type: Schema.Types.ObjectId, 
     ref: 'User' 
    } 
} 

我在节点查找功能,对于用户是一样的东西:

api.find = function(filter, sort, skip, limit){ 
    var callback = arguments[arguments.length - 1]; 
    filter = treatFilter(filter); 
    sort = treatSort(sort); 
    if(callback && typeof callback === 'function'){ 
     User.find(filter).sort(sort).skip(skip).limit(limit).exec(function(err, users){ 
      if(users.length === 0){ 
       callback(err, users); 
      } 
      for(var i = 0, complete = 0; i < users.length; i++){ 
       (function(idx){ 
        var user = users[idx]; 
        var id = user.id; 
        Location.find({owner: id}, function(err, locations){ 
         user.locations = locations; 
         if(++complete === users.length){ 
          callback(err, users); 
         } 
        }); 
       })(i); 
      } 
     }); 
    } 
}; 

我的sort对象必须是什么样的,所以我可以按位置数量进行排序?

谢谢,如果您有任何疑问,我会很乐意来解释我的代码

回答

2

根据这个帖子(mongoose - sort by array length

你必须保持存储位置计数的独立字段 - 不能太开销很大,但有点讨厌保持

我看着成一个虚拟的字段排序,但是这也是不可能的,很可能是非常低效的...

+0

嗯,谢谢。我想到了这一点,但是为了避免麻烦而不得已。我会接受你的答案,如果没有更好的将通过 – 2013-02-17 22:28:04

+2

没有更好的办法。由于您使用的是猫鼬,您可以在使用中间件进行保存之前重新对该数组进行计数。这不是什么大问题,真的。 – 2013-02-18 00:14:31

+0

这是一个好主意。我会尝试 – 2013-02-18 11:38:44

相关问题