猫鼬:按字母顺序排序 [英] Mongoose: Sort alphabetically

查看:95
本文介绍了猫鼬:按字母顺序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个User模型

var User = mongoose.model('Users',
    mongoose.Schema({
        username: 'string',
        password: 'string',
        rights: 'string'
    })
);

我想获取所有用户,并按username字母顺序进行排序.这就是我尝试过的

I want to get all the users, sorted alphabetically by username. This is what I have tried

User.find({}, null, {sort: {username: 1}}, function (err, users) {
    res.send(users);
});

但是,这不会按字母顺序对用户进行排序.如何按字母顺序排序?

However, this does not sort the users alphabetically. How can I sort alphabetically?

编辑 :我感到困惑,因为我期望猫鼬会提供按字母顺序排列"的排序方式,而不是Z> a中的一种方式.基本上,我想基于username.toLowerCase()进行排序.

EDIT: I got confused because I was expecting a "purely alphabetically" sort from Mongoose, not one where Z > a. Basically, I wanted a sort based on username.toLowerCase().

推荐答案

根据评论,问题出在toLowerCase(username)上. MongoDB没有用于复杂排序的内置方法.因此,基本上有两种方法可以解决:

Per the comment the issue turns out to be sorting on toLowerCase(username). MongoDB doesn't have a built in method for complex sorting. So there are essentially two ways to go:

  1. 在架构中添加一个usernameLowerCase字段.如果您需要做很多事情,这是更好的选择.
  2. 使用
  1. Add a usernameLowerCase field to the Schema. This is the better option if you need to do this a lot.
  2. Perform an aggregation with a projection using the $toLower operator to dynamically generate a usernameLowerCase field. This comes with performance and memory caveats, but it may be the more convenient choice.

原始答案:这是一个完整的示例,可以使用问题中的特定代码正确排序.因此,肯定还有其他事情在发生:

Original Answer: Here's a complete example that sorts correctly using the specific code from the question. So there must be something else going on:

#! /usr/bin/node

var mongoose = require('mongoose');
mongoose.connect('localhost', 'test');
var async = require('async');

var User = mongoose.model('Users',
    mongoose.Schema({
        username: 'string',
        password: 'string',
        rights: 'string'
    })
);

var userList = [
    new User({username: 'groucho', password: 'havacigar', rights: 'left'}),
    new User({username: 'harpo', password: 'beepbeep', rights: 'silent'}),
    new User({username: 'chico', password: 'aintnosanityclause', rights: 'all'})
];

async.forEach(userList, 
    function (user, SaveUserDone) {
        user.save(SaveUserDone);
    },
    function (saveErr) {
        if (saveErr) {
            console.log(saveErr);
            process.exit(1);
        }
        User.find({}, null, {sort: {username: 1}}, function (err, users) {
            if (err) {
                console.log(err);
                process.exit(1);
            }
            console.log(users);
            process.exit(0);
        });
    }
);

这篇关于猫鼬:按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆