gpt4 book ai didi

node.js - 在 Mongoose 上定义自定义排序函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:36 25 4
gpt4 key购买 nike

我有一种情况,我想根据某些单词出现的次数,对定义我自己函数的 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'

所以,当我查询“naked cake”时,我想要这样的结果

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

有人知道如何实现这种排序,计算单词的出现次数吗!?

最佳答案

使用Text Search为了执行不区分大小写的文本搜索,它使用分词器和词干算法来有效地查找文本。您必须定义一个 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);
});

关于node.js - 在 Mongoose 上定义自定义排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43430856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com