Home > database >  Unable to create index on mongodb local using mongoose
Unable to create index on mongodb local using mongoose

Time:08-17

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

CodePudding user response:

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();
  • Related