首页 > 解决方案 > MongoError: $text 查询所需的文本索引

问题描述

我正在获取 $text 查询所需的文本索引,因为在使用该模式之前我已经做了索引。有人可以告诉我可能是什么问题吗?还有一个问题我们需要在 mongodb 中删除表来创建索引吗?如果是,那么我将丢失我当前的数据。如何在不删除表的情况下进行索引?

const mongoose = require('mongoose');

let UserSchema = new mongoose.Schema({
    email: String,
    title: String,
});

UserSchema.indexes({ email: 'text', title: 'text' });

run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();

    const UserModel = mongoose.model('user', UserSchema);
    await UserModel.createIndexes();
    const newUser = [
        { email: 'test@test.com', title: 'r' },
        { email: 't@gmail.com', title: '@ro' },
    ];
    const user = await UserModel.create(newUser);
    console.log(user, 'user');
    const index = await UserModel.listIndexes();
    console.log(index);
    const data = await UserModel.find({ $text: { $search: 'test' } }).exec();
    console.log(data);
}

标签: node.jsmongodbmongoosemongoose-schema

解决方案


该函数UserSchema.indexes返回在架构上定义的当前索引。你想要UserSchema.index定义一个新的索引。


推荐阅读