在mongoose上定义自定义的sortingfunction

我有一种情况,我想根据一些单词的出现次数来定义我的数据,从MongoDB中定义我自己的函数。

例如,我有这个模式:

const RecipeSchema = mongoose.Schema({ Title: { type: String }, Content: { type: String }, PublishDate: { type: Date }, }); 

和那些值:

 Title: 'Chocolate Cake', Title: 'Naked Cake', Title: 'Fruit Cake', Title: 'Beef' 

所以,当我查询“裸体蛋糕”时,我想要一个这样的结果

 Title: 'Naked Cake', // 1, because have the two words Title: 'Chocolate Cake', // 2 because have just one word Title: 'Fruit Cake', // 3 because have just one word // beef has no match word 

今天我有这个查询function:

  Recipe .find() .where({ Title: GetQueryExpression(value)}) .sort({ PublishDate: -1 }) .exec(callback); 

GetQueryExpression函数是:

 function GetQueryExpression(value){ var terms = value.split(' '); var regexString = ""; for (var i = 0; i < terms.length; i++) regexString += terms[i] + '|'; regexString = regexString.substr(0, regexString.length - 2); var result = new RegExp(regexString, 'ig'); return result; } 

有人有一些想法如何实现这种sorting,说出这个词的发生!?

使用文本search来执行不区分大小写的文本search,它使用分词器和词干algorithm高效地查找文本。 您必须定义一个text索引,然后在集合的text索引上执行search:

 var mongoose = require('mongoose'); var db = mongoose.createConnection("mongodb://localhost:27017/testDB"); var RecipeSchema = mongoose.Schema({ Title: { type: String }, Content: { type: String }, PublishDate: { type: Date }, }); RecipeSchema.index({ name: 'text', 'Title': 'text' }); var Recipe = db.model('Recipe', RecipeSchema); Recipe.find({ $text: { $search: "naked cake" } }, function(err, res) { console.log(res); });