3

The database action insert now seems to be synchronous returning _id right after the insertion, therefore no callback is needed here.

The question lies on where does the _id being generated (and checked), since this seems to be a fast synchronous action done on miniMongo, yet there is no full list of _id of a certain collection, how’s that possible for miniMongo to check whether the _id is duplicated or not??

Ziac
  • 70
  • 5

1 Answers1

5

When using Collection.insert on the client, the _id is generated on the client using a random uuid algorithm, hence the seemingly perfectly latency compensated client-side insertion.

Collection.insert being implemented as a special case of Meteor.method, we know that at the same time the client simulation is run on the client, a corresponding server operation is triggered, the client document is sent to the server along with its locally generated _id.

On the server, there's a check to see if the _id is correct (truly unique) and the server acknowledge the valid insertion back to the client.

If the client generated _id was not unique after all, then the insert will fail with a "duplicate key error" (this could happen like 0.001% of the time - the probability is even lower, and you would have to resubmit your client form or whatever).

To answer specifically your question, the _id can be generated in the browser in case of a client insert, but it's validity is ultimately checked on the server.

EDIT : I initially assumed that Meteor was trying to recover from the duplicate key error and generate a new key to avoid duplicity and propagate it on the client, I tested the use case and found out I was wrong, thanks @Tom Freudenberg for pointing this out.

saimeunt
  • 22,666
  • 2
  • 56
  • 61
  • 2
    Are you 100% sure about that sequence? What is about setting the _id directly by myself like: `col.insert({ id: 'mykey', ... });`. This is valid and in that case you got a key violation error. From my point of view, the _id is ALWAYS generated (if not given like above) unique by internal Mongo.ObjectID() method (http://docs.meteor.com/#/full/mongo_object_id). So I am nearly sure, that never an _id is changed during or after insert once it is specified. If it doesn't fit there is always an error. – Tom Freudenberg May 08 '15 at 12:04
  • May I ask where did you get this information and really thanks a lot for answering so fast!! – Ziac May 08 '15 at 13:50
  • @Ziac : mainly from reading official Meteor discussion group where MDG would randomly discuss about Meteor internal implementation, also reading directly the source code sometimes. – saimeunt May 08 '15 at 19:21