The PouchDB Manual suggests using Date().toJSON()
to generate a new id for each document. Do all javascript runtimes guarantee that Date().toJSON()
will always be unique?
Asked
Active
Viewed 118 times
3

Ole
- 41,793
- 59
- 191
- 359
-
no, it won't be unique - if you and I run that at exactly the same moment, we'll get exactly the same result. And, `console.log(new Date().toJSON(),new Date().toJSON())` will produce the identical output twice most of the time as well - so, no – Jaromanda X Jan 24 '18 at 05:58
-
`new Date().toJSON() + Math.random() + Math.random()` is more likely to be unique – Jaromanda X Jan 24 '18 at 05:59
-
why aren't you using a salted hash value of fixed length for random id generation + incrementor – Matthew Lagerwey Jan 24 '18 at 06:41
3 Answers
5
The dates only have microsecond precision, so there's no guarantee they will be unique.
The snippet below will give you a number of duplicates in all but the slowest runtime environments:
for (let i = 0; i < 10; i++) {
console.log(new Date().toJSON())
}

Robby Cornelissen
- 91,784
- 22
- 134
- 156
0
I think the PouchDb guide mentioned using dates in that example so that documents would be in date/time order, not that this would ensure uniqueness. In the API you can see that if you do not specify an ID PouchDb will create a unique one for you.

IanC
- 865
- 8
- 11
-
I've always assumed that _id had semantics similar to that of a sql primary key, but perhaps that's not the case? I'll start a new question. – Ole Jan 24 '18 at 19:51
-
https://stackoverflow.com/questions/48430626/must-pouchdb-id-property-values-have-to-be-globally-unique – Ole Jan 24 '18 at 19:56