Node.js 用猫鼬分类阿尔法
我正在尝试通过mongoose 3.6.20进行排序,我收到了一些意想不到的结果Node.js 用猫鼬分类阿尔法,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在尝试通过mongoose 3.6.20进行排序,我收到了一些意想不到的结果 CompanySchema.virtual('name_lower').get(function(){ return this.name.toLowerCase(); }); 我有一份有名字的公司名单。起初我认为可能是以区分大小写的方式进行排序。根据文章,我想这是真的 我现在使用一个虚拟属性来记录排序字段的大小写。然而,我仍然得到了意想不到的结果 CompanySchema.virtual('name_low
CompanySchema.virtual('name_lower').get(function(){
return this.name.toLowerCase();
});
我有一份有名字的公司名单。起初我认为可能是以区分大小写的方式进行排序。根据文章,我想这是真的
我现在使用一个虚拟属性来记录排序字段的大小写。然而,我仍然得到了意想不到的结果
CompanySchema.virtual('name_lower').get(function(){
return this.name.toLowerCase();
});
当我分类时
Company.find().sort({ name_lower: 1 });
我按以下顺序得到它:
更新: 根据答案中提供的信息,我重构了我的模式,以包括一些规范化字段,并连接到文档的pre-save事件中,在这里我更新这些规范化字段,并在将来的所有查询中使用它们进行排序
CompanySchema.pre('save', function(next){
this.normalized_name = this.name;
});
接下来,在我使用的模式中:
var CompanySchema = mongoose.Schema({
...
normalized_name: { type: String, set: normalize },
...
});
其中,
normalize
是一个函数,目前它返回传递给它的值的小写版本。但是,这让我以后可以非常快速地扩展它,并且我可以快速地对可能需要排序的其他字段执行相同的操作。不幸的是,MongoDB和Mongoose目前不支持复杂排序,因此有两个选项:
for
循环,并将每个公司名称更新为小写形式:
db.CompanyCollection.find().forEach(
function(e) {
e.CompanyName = e.CompanyName.toLowerCase();
db.CompanyCollection.save(e);
}
)
更多信息请参见和。我想在这个钩子中指出:
CompanySchema.pre('save', function(next){
this.normalized_name = this.name;
});
您必须调用next()
最后,如果希望将规范化的_名称
保存到数据库中,则预保存挂钩如下所示:
CompanySchema.pre('save', function(next){
this.normalized_name = this.name;
next();
});
从MongoDB v3.4开始,可以使用以下方法完成不区分大小写的排序:
Company.find()
.collation({locale: "en" }) //or whatever collation you want
.sort({name:'asc'})
.exec(function(err, results) {
// use your case insensitive sorted results
});
这个答案似乎对我更有帮助。我必须考虑到与本案有关的发音错误,所以我曾使用<代码>强度:3
您不能对虚拟属性进行排序。好的。很高兴知道。对于我正在尝试做的事情,是否有其他解决方案?或者我必须将名称存储在另一个字段中,但在将其保存到文档之前请将其大小写下来?您可以将您的解决方案作为答案吗@用户2787799