节点 - Mongoose 3.6 - 使用填充字段对查询进行排序

时间:2013-10-17 13:45:28

标签: node.js mongodb mongoose

我正在尝试进行远程网格使用的查询,因此我必须在每个字段上处理sort(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)进行排序时查询正在工作,但是当它是'contact.firstName'时,它不能使它工作(应该是Customer.contact.firstName )。

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

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

无效(似乎对客户的联系人列表进行排序)。

我完全是mongoose(和mongo)的新手。我正在尝试将rails projets移植到node / express。

有没有办法可以通过contact.firstName对我的查询进行排序?

谢谢!

编辑:我最终手动排序(Array.sort),但我真的不喜欢这个解决方案。排序是同步所以它阻止node.js主线程(如果我错了,请纠正我)。

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

1 个答案:

答案 0 :(得分:8)

您无法对虚拟字段或填充字段进行排序,因为这些字段仅存在于您的应用程序对象(Mongoose模型实例)中,但排序是在MongoDB中执行的。

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