fp007
fp007

Reputation: 480

How to remove schema validation in mongoose (mongodb)?

I have MongoDB server version: 5.0.6 installed and used "mongoose": "^6.0.14" to create a model validation. Example of model:

const User = new Schema({
  name: {
    type: String
  },
  relationId: {
    type: Number,
    unique: true,
    required: 'Id in SQL DB'
  },
});

Now I don't need the relationId to be required. Actually I want to delete it from the DB but I can't. And I can't to change the behavior of the validator. I tried:

Modified the Mongoose schema to:

const User = new Schema({
  name: {
    type: String
  }
});

As admin in the DB threw the command:

db.runCommand({ collMod: "users", validator: {}, validationLevel: "off" })

Returns an {ok:1} but when I try to insert a document via Mongoose still has the error: 11000 duplicate key error collection: collection.users index: relationId already exists

I used as well

db.users.updateMany({}, {$unset: {relationId: ''}})

Upvotes: 1

Views: 980

Answers (1)

Abdurrahman AVCI
Abdurrahman AVCI

Reputation: 26

Since you had the unique: true part in the schema definition mongoose has already created a unique index in the database. Removing it from the schema definition doesn't automatically remove the index from the database. You should drop the index manually. You can use syncIndexes to remove the index from the database.

Upvotes: 1

Related Questions