node.js - Node - Mongoose 3.6 - 使用填充字段对查询进行排序

标签 node.js mongodb mongoose

我正在尝试执行远程网格使用的查询,因此我必须处理每个字段的排序(升序、降序)。

以下是架构:

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/

相关文章:

mongodb - 从另一个集合中删除 dbref 元素

mongodb - 在 MongoDB 中查找重复记录

javascript - 使用 Mongoose 通过 EJS 发送 DELETE 请求

arrays - Mongoose :删除引用对象时删除数组中的所有引用对象

node.js - 如何在 2015 年部署生产 meteor 服务器?

javascript - 简单的 NodeJS/Express 单元测试

node.js - 如何在本地计算机上模拟 AWS Parameter Store 进行 lambda 函数开发?

javascript - javascript 数组对象逻辑中的小问题

node.js - 如果字段设置为 null,则恢复为 mongoose 中的默认值

node.js - 查询 mongoose 中的 ObjectId 字段时获取空数组