[英]Index is not getting created, text index required for $text query - mongoose
mongoose: 5.8.9
node: v12.13.0
在模式上设置创建索引后,猫鼬不会创建索引,创建新文档后只有 ID 索引没有新创建的内容。 我已经按照创建索引中提到的文档做了,但我仍然无法弄清楚我在哪里犯了错误。
什么时候
const ads = await Ad.find({ $text: { $search: "something" } })
错误
MongoError: text index required for $text query
at Connection.<anonymous> (/home/usama/Projects/commercial/adex/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js:466:61)
at Connection.emit (events.js:210:5)
at Connection.EventEmitter.emit (domain.js:476:20)
at processMessage (/home/usama/Projects/commercial/adex/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connection.js:384:10)
at Socket.<anonymous> (/home/usama/Projects/commercial/adex/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connection.js:553:15)
at Socket.emit (events.js:210:5)
at Socket.EventEmitter.emit (domain.js:476:20)
at addChunk (_stream_readable.js:308:12)
at readableAddChunk (_stream_readable.js:289:11)
at Socket.Readable.push (_stream_readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
ok: 0,
errmsg: 'text index required for $text query',
code: 27,
codeName: 'IndexNotFound',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
}
我的架构
import { Schema } from 'mongoose'
import mongoosePaginate from 'mongoose-paginate-v2'
import Local from '../index'
const adSchema = new Schema(
{
id: Schema.Types.ObjectId,
creater: Schema.Types.ObjectId,
title: { type: String },
tags: Array,
description: { type: String, maxlength: 4500, },
},
{
timestamps: true,
versionKey: false,
autoIndex: false
}
)
adSchema.index({ title: 'text', description: 'text', tags: 'text' })
adSchema.plugin(mongoosePaginate)
const Ad = Local.model('Ad', adSchema)
export { Ad as default }
在 mongo 外壳上
> myads.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "adex.ads"
}
]
线下:
adSchema.index({ title: 'text', description: 'text', tags: 'text' })
在 mongoose模式(而不是数据库)上正确定义索引。 默认情况下, autoIndex: false
在您的应用程序启动时创建索引(链接),但是您通过使用autoIndex: false
来阻止它。
因此,您必须删除该行或在您的模型上显式运行createIndexes
:
adSchema.index({ title: 'text', description: 'text', tags: 'text' });
const Ad = Local.model('Ad', adSchema);
Ad.createIndexes();
从你需要传递的代码中:>>
const blogPosts = await BlogPostModel.find({ $text: { $search: `"${req.query["your-search-quey"] }"` } })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.