[英]Index is not getting created, text index required for $text query - mongoose
[英]MongoError: text index required for $text query
我正在获取 $text 查询所需的文本索引,因为我在使用该模式之前已经做了索引。 有人可以告诉我可能是什么问题吗? 还有一个问题 mongodb 需要drop table 创建索引吗? 如果是,那么我将丢失我当前的数据。 如何在不删除表的情况下进行索引?
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);
}
function UserSchema.indexes
返回架构上定义的当前索引。 您需要定义新索引的UserSchema.index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.