skip to Main Content

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.

3

Answers


  1. Chosen as BEST ANSWER

    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.


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

    Login or Signup to reply.
  3. 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, 
        })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search