2013-10-17 51 views
1

我想做一个查询使用远程网格,所以我将不得不在每个字段上处理排序(asc,desc)。节点 - 猫鼬3.6 - 排序查询与填充字段

下面是模式:

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)时工作。

中填入fonction的第四个参数是一个选择对象至极可以有一个排序的对象,但是这样做:

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

不工作(似乎排序联系人列表中的用户)。

我完全是猫鼬(和mongo)的新手。我正试图将一个rails projets移植到node/express。

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

谢谢!

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

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

回答

8

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

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

+0

因此,在mongo风格下做到这一点的唯一方法是将我的联系人放入客户集合(Customer.contact = {})中?是node.js和例如mySql有很好的集成吗?有没有好的办法来处理它? – Doum

+0

@Doum对,或者像你一样在你自己的代码中排序。我没有使用MySQL与node.js,但也许开始[这里](http://stackoverflow.com/questions/5818312/mysql-with-node-js)。 – JohnnyHK

+1

我可能太习惯于使用关系数据库......如果我选择将联系人嵌入到客户(customer.contact = {})中,是否有办法在以后获取所有联系人而无需获取所有客户?这样做没有性能问题?例如,客户将拥有一个项目列表,如果我嵌入它们(customer.projetcs = [])并且想要列出我的应用程序中的所有项目,我将不得不像Customer.find()那样执行并获取每个客户只是为了得到他们的项目列表... – Doum