Unique index of multiple fields leading to duplicate error in mongodb and meteor.js

I use mongodb with meteor.js.
To make several fields unique from the collection at the same time, I use the following code

Messages._ensureIndex({ "numbers": 1, "messageListId": 1, "userId": 1},{unique: true , sparse: true});

messageListId and userId can be null (optional). When the number field already exists and I want to insert a new object, Mongo gives the following error:

Error: MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: meteor.messages.$numbers_1_messageListId_1_userId_1  dup key: { : "09355270761", : null, : null } [409]

for example, I want to insert objects below

Messages.insert({numbers:123,messageListId:456,userId:1});

Messages.insert({numbers:123});

I give the above error. How to do it in meteor.js?

I see these links, but my problem is not resolved with their answer (updated)

How to add unique identifier with two columns in mongodb in meteor app?

Creating Multifield Indexes in Mongoose / MongoDB

Error setting composite index

sparse indices and null values ​​in mongo

Thank you for the attention.

+4

All Articles