This question already has answers here:
mongoDB/mongoose: unique if not null
(4 answers)
Closed 5 years ago.
I have an email field set as unique, but it is not required.
The problem is that if the user does not enter anything Mongoose puts "null" in it. This causes duplicates because every user that does not enter the email field will have "null" assigned to it.
What is the standard practice to avoid this?
Thanks
Use a sparse unique index
If a document does not have a value for a field, the index entry for
that item will be null in any index that includes it. Thus, in many
situations you will want to combine the unique constraint with the
sparse option. Sparse indexes skip over any document that is missing
the indexed field, rather than storing null for the index entry.
db.collection.createIndex( { a: 1, b: 1 }, { unique: true, sparse: true } )
More information: https://docs.mongodb.com/v3.0/tutorial/create-a-unique-index/
Related
This question already has answers here:
html5 window.localStorage.getItemItem get keys that start with
(4 answers)
Closed 1 year ago.
I have following types of keys in my localStorage,
Key: Designer-96, Value: true
Key: Designer-76, Value: true
On Page_Load() I want to identify if localStorage contains any keys that start with Designer word, if that's the case then I want to execute certain logic.
Is it possible to iterate through the keys of localStorage in JavaScript and find part of the matching key?
You can get all keys of localStorge using
Object.keys(localStorage)
and you can then use some to check for the existence of a key starts with Designer
const ls = localStorage;
ls.setItem("Designer-96", true);
ls.setItem("Designer-76", true);
const keys = Object.keys(ls);
if (keys.some((k) => k.startsWith("Designer"))) console.log("Key is present");
else console.log("Key is not present");
This question already has answers here:
Add new field to every document in a MongoDB collection
(7 answers)
Closed 1 year ago.
I am trying to add a field to all documents in the database, but I am not sure how to do that. Here is my database
const db = client.schema
How would I update all documents and add a field called tiks (number) in it?
db.yourCollection.update(
{},
{ $set: {"newField": 1} },
false,
true
)
Parameters
Collection to update since you want all {}
Field to set
Upsert - only add when it is not there hence false
Multi - update multiple documents if matches to query hence true
I have a quick question about mongoose schema real quick. Here is the code: https://i.ibb.co/Db8xPMw/5555.png
I tried to create a document without the property "work". It works in the first time, but it didn't start to work on the second time that I do the same thing again.
Do you have any idea?
Basically I create two documents without an "work" property, which causes a duplicate key error. However, I didn't set up unqiue: true though.
Error :
"errmsg" : "E11000 duplicate key error collection: test.user index work_1 dup key: { : null }
From the message it says your collection has an index with name work_1 probably on field work, Since you've created a document without work field then basically you cannot create another document without work field what so ever in the same collection, cause two documents with no work field or even work field with value as null or same cannot exist as it violates unique constraint policies (it says dup key : { : null}) !! Uniques indexes can be created via mongoose schemas or can also be created by manually running queries on database.
Ref : Search for Unique Index and Missing Field in index-unique
So you need to drop the existing index using dropIndex & then if needed recreate it using createIndex. MongoDB would automatically convert a created index to index-multikey (multi-key index - indexes on array fields) if at least one existing document has array value for that indexed field by the time you create index or even if an array value gets inserted for that field in future.
Through code - Drop index : yourSchema.dropIndex({yourFieldName: 1}) && Create index : yourSchema.index({yourFieldName : 1})
NOTE : Just in case if you want to have certain criteria in unique indexes like situation from this question where indexed field can be missing in some documents but it shouldn't be considered as duplicate insertion, then you can take use of partial-indexes (Search for Partial Index with Unique Constraint) which would only index documents where work field exists.
Ex of partial-indexes :-
db.yourCollectionName.createIndex(
{ work: 1 },
{ unique: true, partialFilterExpression: { work: { $exists: true } } }
)
Ref : mongoose-Indexes
so I have a mongoose schema in my node application with two fields: tag and task, and I want to be able to save entries where the combination of both properties doesnt exist yet.
For example: my DB already has the following entries:
{tag:tag1, task:task1}
{tag:tag1, task:task2}
{tag:tag2, task:task1}
I want to be able to create {tag:tag2, task:task2}, but not {tag:tag1, task:task1} again, so I guess I cant use primary or unique in any of those fields, since they can repeat, except when their combination already exists
so which query should I use to save? Or should I find if it already exists first?
Use Unique Compound Indexing
db.users.createIndex( { "tag": 1, "task": 1 }, { unique: true } )
For more info visit the Link
This question already has an answer here:
How can you specify the order of properties in a javascript object for a MongoDB index in node.js?
(1 answer)
Closed 8 years ago.
To define a compound index:
db.collection.ensureIndex( { orderDate: 1, zipcode: -1 } )
It suddenly dawned on me : are the fields of a JS object ordered?
Is there an implicit assumption that orderDate comes first? I'm quite surprised it doesn't use an array instead.
For mongoose, we use :
schema.index({a:1, b:1})
How can we ensure this object is transmitted to the mongo server with the fields ordered as specified in the code?
This post says fields are not ordered. Does JavaScript Guarantee Object Property Order?
Is it acceptable style for Node.js libraries to rely on object key order?
From the documentation
Indexes store references to fields in either ascending (1) or descending (-1) sort order. For single-field indexes, the sort order of keys doesn’t matter because MongoDB can traverse the index in either direction. However, for compound indexes, sort order can matter in determining whether the index can support a sort operation.
So if you created your index using
db.collection.ensureIndex( { orderDate: 1, zipcode: -1 } )
the object will be transmitted to the mongo server with the fields as ordered also note that using
db.collection.ensureIndex( { orderDate: 1, zipcode: -1 } )
and
db.collection.ensureIndex( { zipcode: -1 , orderDate: 1} )
will create two different compound indexes