1

I'm creating a new schema in mongoose and trying to take input from user. I want that no duplicate entry is getting updated for serverIP, for that unique : true is added. But this is not working as expected and duplicates entries are getting through.

Below is the example code:-

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var ServerSchema = new Schema({
    serverIp: { type : String , unique : true },
    Name:  { type: String },
    serverType: {type: String , required : true },
    created_date: {type: Date, default: Date.now},
    updated_date: {type: Date, default: Date.now}
});

I've checked CreateIndex functionality for this but don't know how to implement this with my code.

I have never worked on back-end part, so please excuse if this is a novice question.

Community
  • 1
  • 1
TheMightyNight
  • 161
  • 1
  • 2
  • 13

4 Answers4

3

Try to create unique index on the field serverIp,

ServerSchema.index({serverIp: 1}, {unique: true});
RaR
  • 3,075
  • 3
  • 23
  • 48
1

You have to Restart mongo after creating schema.

Mithilesh Gupta
  • 2,800
  • 1
  • 17
  • 17
1

It seems that you have done unique indexing (at schema level) after inserting some records in db.

Please follow below steps to avoiding duplicates.

1) drop your db:

$ mongo

> use <db-name>;

> db.dropDatabase();

2) now do indexing at schema level which you have done already.

it will avoid duplicate record insertion with same field serverIp (in your case) value.

And for ensuring the index, use command

> db.db_name.getIndexes()
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Siyaram Malav
  • 4,414
  • 2
  • 31
  • 31
1

I had the same issue trying to add unique: true for my article titles. I dropped the db, restarted my local server and restarted mongo in my terminal. That is the only thing that seemed to work for me.

Gruebes
  • 41
  • 5