【发布时间】:2022-12-22 05:05:15
【问题描述】:
所以我想在我的 MongoDB 数据库中搜索我的博客集合。我想按标题搜索,我在模式文件中用 mongoose 创建了索引。一切都很好,但是如果我有一个博客的标题是这样的:“averylongtitlewithoutspaces”,除非我输入整个标题,否则它不会搜索它。它适用于空格,因此搜索“非常”会返回“带空格的非常长的标题”。如何让 mongo 搜索带空格的文本?
这是我的架构文件
import { Schema, model } from "mongoose";
interface IBlog {
title: String,
content: String,
author: String,
authorId: Schema.Types.ObjectId,
shortContent: String,
image: String
}
const BlogSchema = new Schema<IBlog>({
title: {
required: true,
type: String
},
content: {
required: true,
type: String
},
author: {
required: true,
type: String
},
authorId: {
required: true,
type: Schema.Types.ObjectId,
ref: "Account"
},
shortContent: {
required: true,
type: String
},
image: {
requred: true,
type: String
}
}, {
timestamps: true
});
BlogSchema.index({ title: "text" }, {default_language: "none"});
export const Blog = model("Blog", BlogSchema, "blogs");
我正在做的查询:
const blogs = await Blog.find({ $text: { $search: req.params.input } });
【问题讨论】:
-
请添加您正在进行的查询。
-
@Ayzrian 补充说,抱歉我完全忘记了。
-
您可以使用 {name:/.*sam.*/} 等正则表达式进行搜索