NodeJS Express操作MongoDB搜索关键词报错:Minutes.index不是函数
问题调试方案
报错根因
index() 是Mongoose Schema的实例方法,只能在Schema编译为Model之前调用,你将该方法直接在已编译完成的Minutes Model实例上调用,因此触发is not a function报错。
修正步骤
1. 调整索引声明位置
将文本索引定义移到Schema声明阶段、编译Model之前,修正后的Schema代码如下:
const MinutesSchema = new Schema({ minute_id :{ type: Number, required: true }, minute_type :{ type: String, default: "", }, description :{ type: String, default: "" }, }, {collection:"pm_meeting_minutes"}); // 在Schema实例上声明文本索引,必须放在model编译之前 MinutesSchema.index({ minute_type: "text" }); const Minutes = mongoose.model('pm_meeting_minutes', MinutesSchema); exports.Minutes = Minutes;
也可以直接在字段属性中声明索引:
minute_type :{ type: String, default: "", index: "text" },
2. 修正查询逻辑
删除业务代码中错误的Model索引调用,修正后的查询代码如下:
exports.getSearch = () => { return Minutes.find( { $text: { $search: "Issue" } } ) }
补充说明
首次添加索引后Mongoose会自动在MongoDB中创建对应索引,首次查询可能有短暂延迟,建议提前确认MongoDB侧索引已创建完成。
如果数据量较小,不需要启用全文索引,也可以直接用正则查询实现包含匹配,无需额外建索引:
exports.getSearch = () => { // 加$options:"i"可实现大小写不敏感匹配,不需要可删除 return Minutes.find({ minute_type: { $regex: "Issue", $options: "i" } }) }
内容的提问来源于stack exchange,提问作者Student31
相关产品推荐
相关产品推荐

