2

リモート グリッドで使用されるクエリを実行しようとしているので、すべてのフィールドで並べ替え (昇順、降順) を処理する必要があります。

スキーマは次のとおりです。

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 関数の 4 番目のパラメーターは、並べ替えオブジェクトを持つことができるオプション オブジェクトですが、次のようにします。

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

機能していません (顧客の連絡先リストを並べ替えているようです)。

私はマングース(およびモンゴ)にまったく慣れていません。Rails プロジェクトを node/express に移植しようとしています。

contact.firstName でクエリを並べ替える方法はありますか?


編集:手動でソート(Array.sort)を行うことになりましたが、このソリューションは本当に好きではありません。並べ替えは同期であるため、node.js メインスレッドをブロックします (間違っている場合は修正してください)。

わからないことがありますか?データセットの並べ替えは、アプリケーションではなくデータベースの問題です... Rails アプリケーションを node.js に変換することに多くの期待を寄せていましたが、一部の標準操作 (グリッドのページング) を実装するのは本当に難しいようです!

4

1 に答える 1