Home > database >  mongodb not detecting unique value in my node js project
mongodb not detecting unique value in my node js project

Time:02-06

I'm working on mongodb with node js and I realized that even though I used the unique true property on unique fields in my project, I realized that it doesn't work, what is the reason?

my code is like this

const CourseSchema = new Schema({
  name: {
    type: String,
     required : true,
     unique:true
   
  },
  description: {
    type: String,
    required: true,
    trim: true,
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

i want to prevent this code from saving duplicate usernames.

CodePudding user response:

Such a check if not directly possible with the mongoDB library. However it is supported out of the box if you use mongoosejs

CodePudding user response:

It may be possible that you already have duplicate values in your document before defining this property Delete the messed data from the MongoDB collections, or make sure that mongodb auto indexing is true

mongoose.connect('url', { useNewUrlParser: true, useCreateIndex: true, autoIndex: true, })

CodePudding user response:

I tried many ways, but I realized that this problem is version-related, I found the solution by updating the version, thank you for your solution support.

  • Related