问题
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?
回答1:
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())
}
回答2:
In case of distributed system, We can also use this eventid module.
回答3:
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.
来源:https://stackoverflow.com/questions/48415665/will-new-date-tojson-always-be-unique-in-javascript