簡體   English   中英

節點 - Mongoose 3.6 - 使用填充字段對查詢進行排序

[英]Node - Mongoose 3.6 - Sort query with populated field

我正在嘗試執行遠程網格使用的查詢,因此我必須處理每個字段的排序(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);
};

該查詢在對“姓名”(即 Customer.name)或“地址”(Customer.address)進行排序時有效,但在“contact.firstName”(應為 Customer.contact.firstName)時無法正常工作.

populate 函數的第四個參數是一個選項對象,它可以有一個排序對象,但這樣做:

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

不工作(似乎對客戶的聯系人列表進行排序)。

我對貓鼬(和 mongo)完全陌生。 我正在嘗試將 Rails 項目移植到 node/express。

有沒有辦法按contact.firstName 對查詢進行排序?


編輯:我最終手動排序(Array.sort),但我真的不喜歡這個解決方案。 Sort 是同步的,所以它會阻塞 node.js 主線程(如果我錯了,請糾正我)。

有什么我不明白的嗎? 排序數據集對我來說是一個數據庫問題而不是應用程序......我對將我的 rails 應用程序轉換為 node.js 抱有很大希望,但似乎一些標准操作(分頁網格)真的很難實現!

您無法對虛擬字段或填充字段進行排序,因為這些字段僅存在於您的應用程序對象(Mongoose 模型實例)中,但排序是在 MongoDB 中執行的。

這是 MongoDB 不支持連接導致的主要限制之一。 如果您的數據是高度相關的,那么您應該考慮使用關系數據庫而不是 MongoDB。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM