我正在尝试执行远程网格使用的查询,因此我必须处理每个字段的排序(升序、降序)。
以下是架构:
var customerSchema = new mongoose.Schema({
status: {type: mongoose.Schema.Types.ObjectId, ref: 'Status'},
contact: {type: mongoose.Schema.Types.ObjectId, ref: 'Contact'}
}, { collection: 'Customer' });
customerSchema.virtual('contactName').get(function () {
if (this.contact && this.contact.get) {
return this.contact.get('firstName') + ' ' + this.contact.get('lastName');
}
return '';
});
customerSchema.virtual('statusName').get(function () {
if (this.status && this.status.get) {
return this.status.get('name');
}
return '';
});
customerSchema.set('toJSON', { virtuals: true });
customerSchema.set('toObject', { virtuals: true });
mongoose.model('Customer', customerSchema);
// STATUS
var statusSchema = new mongoose.Schema({}, { collection: 'Status' });
mongoose.model('Status', statusSchema);
// CONTACT
var contactSchema = new mongoose.Schema({
firstName: String,
lastName: String
}, { collection: 'Contact' });
mongoose.model('Contact', contactSchema);
这是查询:
exports.customerList = function (predicate ,callback){
if (!predicate) predicate = 'name';
var Customers = mongoose.model( 'Customer' );
Customers.find()
.select('name phone address status contact contactName statusName')
.populate('status', 'name')
.populate('contact', 'firstName lastName')
.sort(predicate)
.exec(callback);
};
查询在按“名称”(即 Customer.name)或“地址”(Customer.address)排序时有效,但在按“contact.firstName”(应为 Customer.contact)排序时无法正常工作.firstName)。
populate 函数的第四个参数是一个选项对象,它可以有一个排序对象,但这样做:
.populate('contact', 'firstName lastName', null, { sort {'firstName': 1}})
不起作用(似乎对客户的联系人列表进行排序)。
我对 mongoose (和 mongo)完全陌生。我正在尝试将 Rails 项目移植到 Node/Express。
有没有办法可以按 contact.firstName 对查询进行排序?
<小时/>编辑:我最终手动进行了排序(Array.sort),但我真的不喜欢这个解决方案。排序是同步的,因此它会阻塞 node.js 主线程(如果我错了,请纠正我)。
有什么我不明白的地方吗?对我来说,对数据集进行排序是数据库问题,而不是应用程序...我对将 Rails 应用程序转换为 Node.js 抱有很大希望,但似乎某些标准操作(对网格进行分页)确实很难实现!
最佳答案
您无法对虚拟字段或填充字段进行排序,因为这些字段仅存在于您的应用程序对象(Mongoose 模型实例)中,但排序是在 MongoDB 中执行的。
这是 MongoDB 不支持联接导致的主要限制之一。如果您的数据高度相关,那么您应该考虑使用关系数据库而不是 MongoDB。
关于node.js - Node - Mongoose 3.6 - 使用填充字段对查询进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19428471/