createIndex in mongoose
createIndex
is a function for Mongodb.
In Mongoose it is renamed to index
Item.index({ "createdAt": 1 }, { expireAfterSeconds: 3600 })
Two ways to create index. First
const Schema = mongoose.Schema;
let user = new Schema({
email: {
type: String,
required: true,
index: true //---Index----
}
});
module.exports = mongoose.model('User', user);
Second method
const Schema = mongoose.Schema;
let user = new Schema({
email: {
type: String,
required: true
}
});
user.index({ email: 1 }); //---Index----
module.exports = mongoose.model('User', user);
When doing this if you are getting a warning(I am using MongoDB: 4.2.8 and Mongoose: 5.9.20)
DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Then you might need to add 'useCreateIndex: true' to your mongoose.connect
mongoose.connect(Uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});