I am getting text index required for $text query where as i already did index before using that schema. Can someone tell me what could be the issue?. One more question Do we need to drop table in mongodb to create index? if yes then i will loose my current data. how can i do indexing without dropping the 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);
}
The function UserSchema.indexes
returns the current indexes that are defined on the schema. You want UserSchema.index
that defines a new index.