node.js - 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);
}
解决方案
该函数UserSchema.indexes
返回在架构上定义的当前索引。你想要UserSchema.index
定义一个新的索引。
推荐阅读
- multithreading - 互斥量和二进制信号量之间的实际区别
- matlab - 可以提高 Matlab export_fig 中点的分辨率吗?
- python - Yelp 抓取,Python 难以获得汽车旅馆
- android - App Bar 不会根据导航组件中的 Fragment 更改
- r - 如何通过多个数据帧循环功能
- mysql - 涉及 COUNT() 和 LOWER() 的 Spring JPA 查询
- python - Openpyxl - 给单元格一个标识符
- python - 当值更改时,如何使我的 Kivy 标签动态更新?
- django - yoyo 迁移和 django 迁移有什么区别?
- java - 使用字符检查二维数组中的某些单词(作业)