E11000 duplicate key error index in mongodb mongoose

前端 未结 25 2001
自闭症患者
自闭症患者 2020-11-22 05:49

Following is my user schema in user.js model -

var userSchema = new mongoose.Schema({
    local: {
        name: { type: String },
         


        
25条回答
  •  心在旅途
    2020-11-22 06:22

    I want to explain the answer/solution to this like I am explaining to a 5-year-old , so everyone can understand .

    I have an app.I want people to register with their email,password and phone number . In my MongoDB database , I want to identify people uniquely based on both their phone numbers and email - so this means that both the phone number and the email must be unique for every person.

    However , there is a problem : I have realized that everyone has a phonenumber but not everyone has an email address .

    Those that don`t have an email address have promised me that they will have an email address by next week. But I want them registered anyway - so I tell them to proceed registering their phonenumbers as they leave the email-input-field empty .

    They do so .

    My database NEEDS an unique email address field - but I have a lot of people with 'null' as their email address . So I go to my code and tell my database schema to allow empty/null email address fields which I will later fill in with email unique addresses when the people who promised to add their emails to their profiles next week .

    So its now a win-win for everyone (but you ;-] ): the people register, I am happy to have their data ...and my database is happy because it is being used nicely ...but what about you ? I am yet to give you the code that made the schema .

    Here is the code : NOTE : The sparse property in email , is what tells my database to allow null values which will later be filled with unique values .

    var userSchema = new mongoose.Schema({
      local: {
        name: { type: String },
        email : { type: String, require: true, index:true, unique:true,sparse:true},
        password: { type: String, require:true },
      },
      facebook: {
        id           : { type: String },
        token        : { type: String },
        email        : { type: String },
        name         : { type: String }
      }
    });
    
    var User = mongoose.model('User',userSchema);
    
    module.exports = User;

    I hope I have explained it nicely . Happy NodeJS coding / hacking!

提交回复
热议问题