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

Dou*_*oum 2 mongoose mongodb node.js

我正在尝试进行远程网格使用的查询,因此我将不得不在每个字段上处理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);
Run Code Online (Sandbox Code Playgroud)

这是查询:

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);
};
Run Code Online (Sandbox Code Playgroud)

当对'name'(所以Customer.name)或'address'(Customer.address)进行排序时查询正在工作,但是当它是'contact.firstName'(应该是Customer.contact.firstName)时,它无法工作.

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

.populate('contact', 'firstName lastName', null, { sort {'firstName': 1}})
Run Code Online (Sandbox Code Playgroud)

不工作(似乎对客户的联系人列表排序).

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

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

谢谢!

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

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

Joh*_*yHK 9

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

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

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