0

I am trying to create custom index on MongoDB but it is not creating when I check on mongodb-compass and via command line.

This is Mongoose model

import Mongoose from "mongoose";
// import encrypt from "mongoose-encryption";
import dotenv from "dotenv";
import path from "path";

const __dirname = path.resolve();

dotenv.config({ path: __dirname + "/.env" });

const signupSchema = new Mongoose.Schema(
  {
    name: { type: String, required: [true, "name required"] },
    email: {
      type: String,
      required: [true, "email required"],
      unique: true,
      index: true,
    },
    phoneNumber: {
      type: Number,
      required: [true, "phone number required"],
      unique: true,
      index: true,
    },
    currentLocation: {
      type: String,
      required: [false, "current location required"],
    },
    password: { type: String, required: [true, "password requred"] },

    createdDate:{
      type:Date,
      default:Date.now
    },
  },
  {
    timestamps: true,
    timeseries: true,
  }
);

// const secretkey = process.env.MY_SECRET_KEY;

// signupSchema.plugin(encrypt, { secret: secretkey });

signupSchema.index({email:1,type:1})

const SignUpModel = Mongoose.model("SignUp", signupSchema);
export default SignUpModel;

My index.js

mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/naukridb',{
    useNewUrlParser:true,
    useUnifiedTopology:true,
 
})
mongoose.pluralize(null)

Compass Image to see index not created even when defined in model:

enter image description here

This is my command line to check:

enter image description here

No index is created on email and phone number, and unique instance is also not working.

Tried and tested:

Mongoose create multiple indexes
Mongoose not creating index
Mongoose Not Creating Indexes
Mongoose does not create text index
mongoose index don't create
Mongoose Secondary Index is not created

But no solution is working. My MongoDB version is 5.0.10.

halfer
  • 19,824
  • 17
  • 99
  • 186
James
  • 1,124
  • 3
  • 17
  • 37

1 Answers1

1

Looks like this is caused by setting timeseries : true on the schema. I'm not sure if this is a Mongoose issue, a MongoDB issue, or intended behaviour.

You can ensure your secondary indexes get created by using ensureIndexes:

const SignUpModel = Mongoose.model("SignUp", signupSchema);
await SignUpModel.ensureIndexes();
robertklep
  • 198,204
  • 35
  • 394
  • 381