gpt4 book ai didi

node.js - 未创建索引,$text 查询需要文本索引 - mongoose

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

mongoose: 5.8.9
node: v12.13.0

设置在架构上创建索引后,mongoose 不会创建索引,创建新文档后只有 ID 索引,没有新创建的内容。我已经按照creating index提到的文件进行了操作但我仍然不知道我在哪里犯了错误。

何时

 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 shell 上

> myads.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "adex.ads"
}
]

最佳答案

下一行:

adSchema.index({ title: 'text', description: 'text', tags: 'text' })

在 Mongoose 架构上正确定义索引(而不是在数据库上)。默认情况下, Mongoose 会在应用程序启动时创建索引 ( link ),但是您可以使用 autoIndex: false 来阻止它。

因此,您必须删除该行或在模型上显式运行 createIndexes:

adSchema.index({ title: 'text', description: 'text', tags: 'text' });
const Ad = Local.model('Ad', adSchema);
Ad.createIndexes();

关于node.js - 未创建索引,$text 查询需要文本索引 - mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59920729/

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