0

I am facing problem while working with mongoose. unique:true is not working for me. Please have a look at the following schema which i have created.

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
  username:{
     type:String,
     required:true,
     trim:true,
     unique:true   
  },
  firstName: {
     type:String,
     required:true
  },
  lastName: {
     type:String,
     required:true
  },
  createDate:{
     type:Date,
     default:Date.now(),
     required:true
  }
});

userSchema.methods.combineAtTheEnd = function(){
  this.username = this.firstName + this.lastName;
  return this.username;
}

module.exports = mongoose.model('users',userSchema);

And I imported that schema into another file like that.

var mongoose = require('mongoose');
var url = 'mongodb://localhost/test'; 
var userSchema = require('./usermodel');

mongoose.connect(url,function(err){
  if(err){
    console.log(err);
  } else{
    console.log('successfully connected to mongo db');
  }
});

var userModel = new userSchema({
  firstName:'rajat',
  lastName:'madaan'
});

userModel.combineAtTheEnd(function(err,username){
  if(err){
    console.log('Error at the custom method.');
  }else{
    console.log(username);
  }
});

userModel.save(function(err){
  if(err){
    console.log('Error while saving data');
  }else{
    console.log('Successfully Inserted Data');
  }
})

can anyone please help me , what is wrong and how to solve it.

Rajat
  • 486
  • 1
  • 10
  • 35
  • 1
    what is the issue here? are you getting any error or what? – Ashh Jul 15 '18 at 16:20
  • 1
    Possible duplicate of [Mongoose Unique index not working!](https://stackoverflow.com/questions/5535610/mongoose-unique-index-not-working) – Rick Jul 15 '18 at 16:23
  • I need to get the error message for that , Because i defined unique key constraint for the username.It is saving same username everytime and not giving me the error of duplicate username. – Rajat Jul 15 '18 at 16:23

1 Answers1

0

It is fixed guys , I just Deleted My Collection(table) and again try it . Now It is giving me error of Duplicate Value.

Thanks.

Rajat
  • 486
  • 1
  • 10
  • 35