在这种情况下,我希望根据某些单词出现的次数,从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今天我有一个查询函数:
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;
}有人知道怎样才能做到这样,才能看出单词的出现!?
发布于 2017-04-15 22:50:09
使用文本搜索来执行不区分大小写的文本搜索,它使用标记器和词干算法来高效地查找文本。您必须定义一个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);
});https://stackoverflow.com/questions/43430856
复制相似问题