节点 – Mongoose 3.6 – 使用填充字段sorting查询

我试图做一个远程网格使用的查询,所以我将不得不处理sorting(asc,desc)在每个领域。

这里是模式:

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); }; 

查询在对“name”(如Customer.name)或“address”(Customer.address)进行sorting时工作,但在“contact.firstName”(应该是Customer.contact.firstName)时无法使其工作。

填充函数的第四个参数是一个可以有一个sorting对象的选项对象,但这样做:

 .populate('contact', 'firstName lastName', null, { sort {'firstName': 1}}) 

没有工作(似乎sorting客户的联系人列表)。

我对mongoose(和mongo)完全陌生。 我正试图将一个rails projets移植到node / express。

有没有办法,我可以通过contact.firstNamesorting我的查询?

谢谢!

编辑:我结束了做手动sorting(Array.sort),但我真的不喜欢这个解决scheme。 sorting是同步,所以它阻止node.js主线程(纠正我,如果我错了)。

有什么我不明白? sorting数据集对于我来说是一个数据库问题,而不是应用程序…我将我的rails应用程序转换为node.js的希望很大,但似乎有些标准操作(分页)真的很难实现!

您不能sorting虚拟字段或填充字段,因为这些字段只存在于您的应用程序对象(Mongoose模型实例)中,但sorting在MongoDB中执行。

这是MongoDB不支持连接的关键限制之一。 如果你的数据是高度关联的,那么你应该考虑使用关系数据库而不是MongoDB。