I am trying to add unique documents in the collection. However the problem is I want to decide uniqueness based on 2 fields. So I found a solution for it online. What confuses me is, What is the purpose ofINDEX
here? In RDBMS index is usually the word used for row id, what does this mean here and how does it affect the uniqueness?
var patientSchema = mongoose.Schema({
name : String,
fatherOrHusbandName : String,
address : String,
});
patientSchema .***index***({ email: 1, sweepstakes_id: 1 }, { unique: true });
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.
for more details see this documentation .
Don't be confused after reading this document because this document uses createIndex
and you're code uses index
. createIndex
is for MongoDB and index
is for mongoose that internally executes MongoDB operations.
If you have no data in your database then it will work fine
patientSchema .index({ email: 1, sweepstakes_id: 1 }, { unique: true });
but if you have some data in the database with duplicate items then you should use dropDups
keyword to make it a unique index.
But one thing you should know before use dropDups
. If you use dropDups: true
and you have some data with duplicate value then keep one document in your database and all the other data will be deleted (duplicate data).
Like:
patientSchema .index({ email: 1, sweepstakes_id: 1 }, { unique: true, dropDups: true });
It actually has the same purpose like indexes in RDBMS. You just have to think in some mongo-terminology. In mongodb instead of Tables, you have collections, instead of rows, you have documents.
With mongoose you defined a schema for a collection 'Patient', within this collection(index belongs to Patient collection) you defined a unique index
on the document properties email
and sweepstakes_id
.
Every time you save a document in the Patient collection, mongodb makes sure that a document which has the email and sweepstakes_id
properties set, those 2 properties will be unique among all other documents.
So, instead of 'rows', think in 'documents'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With