Similoluwa Odeyemi
Similoluwa Odeyemi

Reputation: 409

How do I change mongoose schema from unique true to unique false

In the code below, the commented email schema was the previous, I no longer want the email to be required, and unique, it should be optional.

I get an error saying duplicate, of null "E11000 duplicate key error collection: mydb.lists index: email_1 dup key: (email: null)"

const mongoose = require("mongoose");    
const { Schema } = mongoose;

const alliedSchema = new Schema(
  {
    name: String,
    phone: String,
    email: {
        unique: false,
        type: String
    },
    // email:{
    // type: String,
    // unique: true,
    // required: true,
    // lowercase: true,
    // validate(value){
    //     if(!validator.isEmail(value)){
    //         throw new Error('Email is invalid')
    //     }
    // }
    // },
    picture: {
      type: String,
      default: "https://www.dialadocdirect.org/app/storage/images/noimage.jpg",
    },
    location: String,
    type: String,
    verified: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);


module.exports = mongoose.model("allied", alliedSchema);

Upvotes: 3

Views: 2564

Answers (2)

Newtocoding1211
Newtocoding1211

Reputation: 21

Go to your Mongodb database from there to indexes delete it from there. You won’t get this error anymore it happens when ever key initialised with unique true index get created even if you change it latter you will have this same duplication error.

Upvotes: 2

Gynteniuxas
Gynteniuxas

Reputation: 7093

Indexes are not automatically removed, so, even if you comment out schema, your indexes will remain. There are at least a couple of possible solutions:

  1. If you have access to Mongo database, then you can execute db.getCollection('allied').dropIndexes() and restart an application. Mongoose will automatically create new indexes that don't exist in collection (in this, it would re-create all but unique).
  2. If you don't have access to database, you can also execute something like this: await alliedModel.syncIndexes(); (really depends on how you create a new model but alliedModel should be the model that is associated with alliedSchema). This will simply synchronizes all indexes according to Mongoose Schema and will only drop unique attribute but leave all other indexes intact.

Upvotes: 6

Related Questions