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

标签 node.js mongodb mongoose

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

相关文章:

php - Zend Framework 的 NoSQL 解决方案?

node.js - 无法访问 Mongoose 保存回调中的变量

javascript - 如何通过 app.js 将另一个 .js 文件所需的函数传递到 index.ejs View

Node.JS 加载一个 html 页面,填写表单,然后按下提交按钮

node.js - 这个 mongoose 部分更新有什么不正确的地方

mongodb - 使用 Pig 将 HDFS 数据存储到 MongoDB

node.js - 从对象 ID 数组中查找用户详细信息

node.js - 图像未从 Node js中的数据库中删除

node.js - 在 Cypress 中模拟网络请求

javascript - 在并发且没有多处理的情况下,代码按什么顺序执行?