I have some records like:
{
name: "Acme co."
add4: "",
nationalNumber: "+13412768376"
}, {
name: "Acme Inc.",
add4: "6345",
nationalNumber: ""
}
And I'm attempting to insert them into collection, but only if they are unique. I'm checking for unique by looking for duplicate:
- nationalNumber (if field isn't empty or null)
- name + add4 (if both fields aren't empty or null)
I have this code in my nodeJs app:
await db.collection('mergedcompany').createIndex(
{ nationalNumber: 1},
{ unique: true },
{ partialFilterExpression: {nationalNumber: {$exists: true}}}
);
await db.collection('mergedcompany').createIndex(
{ name: -1, add4: -1},
{ unique: true },
{ partialFilterExpression:{ name: {$exists: true}, add4: {$exists: true}}}
);
And looping over records and inserting:
try {
await db.collection('mergedcompany').insertOne(record);
} catch (e) {
sails.log.error(e);
}
All records are getting inserted, even if there are duplicate fields and defined in the unique index. If I remove the "partial" filter from the index, mongo then starts throwing errors like it should. But when I include the partial, no errors are thrown and all records are inserted, regardless if duplicate data.
What do I need to do to make this work?