How to avoid duplicates in the mongoose

advertisements

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.


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()