Author | Message |
---|---|
Victor
Posts: 23
|
Posted 23:32 Nov 22, 2018 |
Hi. I have an issue that's been confusing me for a while now. I have this bit in my userSchema (Not related to our assignment)
But when I insert more than one user to my database, I get this error: E11000 duplicate key error collection: db_name.users index: reset_tokens_1 dup key: { : undefined }. I'm confused because I thought the 'sparse: true' ensures I can have multiple users with no ' How do I fix this? |
cysun
Posts: 2935
|
Posted 08:12 Nov 23, 2018 |
unique/sparse work on individual properties, but I'm not sure how Mongoose handles them or what they even mean when applied to array elements. Start with an empty database, run your Mongoose code so the collections are created. In MongoDB Compass, select the users collection, then the Indexes tab, and see what indexes are created and if the sparse property is set on the reset_tokens_1 index.
|
Victor
Posts: 23
|
Posted 09:48 Nov 23, 2018 |
Both the unique and sparse indexes are created. |
cysun
Posts: 2935
|
Posted 09:49 Nov 23, 2018 |
Show a screenshot. |
Victor
Posts: 23
|
Posted 10:06 Nov 23, 2018 |
I'm about to place a property inside the array. It worked for another schema I have. I'll check if it works here too. |
cysun
Posts: 2935
|
Posted 10:12 Nov 23, 2018 |
MongoDB documentation says "Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value". In this case the indexed field is reset_tokens, which means (as I understand) that even if reset_tokens is null or an empty array (i.e. []), it'll still be indexed. |
Victor
Posts: 23
|
Posted 10:14 Nov 23, 2018 |
It works. My userSchema now looks like this:
The index looks like this now reset_tokens.token_1: (unique and sparse) |