2017-04-15 13 views
1

私は、自分の関数を定義するmongodbから、いくつかの単語の出現数に基づいてデータをソートしたいと思う状況があります。mongooseでカスタムソート関数を定義しています

例えば、私はこのスキーマを持っている:

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 

今日私はこのクエリ機能を持っています:

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; 
} 

誰かが言葉の発生をcouting、その種を達成するためにどのようにいくつかのアイデアを持っています!

答えて

2

Text Searchを使用して大文字と小文字を区別しないテキスト検索を実行すると、tokenizer &ステミングアルゴリズムを使用してテキストを効率的に検索します。 textインデックスを定義する必要があり、検索はtextコレクションのインデックスで行われます。

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); 
}); 
関連する問題