Mongoose:sort - 显示参数等于[value]的结果

时间:2016-05-05 07:02:00

标签: node.js mongodb mongoose

在我的数据库中,每个用户创建了一部电影为电影做出了贡献两者。

我想从某个用户参与(创建或贡献)的数据库中提取所有文档。

但我想对结果进行排序:

  1. 他创作和贡献的电影首先出现。
  2. 他创作的电影显示第二个
  3. 他参加的电影最后出现。
  4. 这是我的电影架构:

    var movieSchema = mongoose.Schema({
        _creator: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
        movieName: String,
        credits: [{
            who: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
            what: {String} //writer,director,composer, etc.
        }]
    });
    

    这是我检索电影列表的代码,但我不知道如何根据我的标准对其进行排序。

    Movie
        //find movies that user with id [id] either created or was credited in(participated)
        .find({$or:[ {'_creator':id}, {'credits.who':id}]})
        .exec(function (err,movies) {
    
        })
    

    你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

要对电影进行排序,您可以使用数组的排序方法,如下所示:

var movies = [
    { created: 'user1', contrib: 'user2' },
    { created: 'user2', contrib: 'user1' },
    { created: 'user1', contrib: 'user1' }
];

var user = 'user1';

movies.sort(function(movie1, movie2) {

    var m1 = 0;
    if (movie1.created === user) m1 = 2;
    if (movie1.contrib === user) m1++;

    var m2 = 0;
    if (movie2.created === user) m2 = 2;
    if (movie2.contrib === user) m2++;

    return m2 - m1;
});

console.log(movies);

//output> first movies user has created and contributed
//        then movies user created
//        then movies user contributed to
[ { created: 'user1', contrib: 'user1' },
  { created: 'user1', contrib: 'user2' },
  { created: 'user2', contrib: 'user1' } ]

我相信上面的代码是自我解释的