Search code examples
node.jsmongodbmongoosemongoose-schema

is createdAt unique or not in mongoose timestamp?


Is createdAt created by the mongoose timestamps feature unique or not if we create multiple documents using mongoose?


Solution

  • No, there is no enforcement of uniqueness enforced at the DB level for these fields.

    From a usage perspective we can look at mongoose source code to see how these fields are created:

    const createdAt = handleTimestampOption(timestamps, 'createdAt');
    const updatedAt = handleTimestampOption(timestamps, 'updatedAt');
    const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ?
      timestamps.currentTime :
      null;
    const schemaAdditions = {};
    
    schema.$timestamps = { createdAt: createdAt, updatedAt: updatedAt };
    
    if (updatedAt && !schema.paths[updatedAt]) {
      schemaAdditions[updatedAt] = Date;
    }
    

    So we don't need to follow the entire flow to understand this is created in memory. Basically when you create a new document the schema creates these two defaulted fields if you have timestamps enabled. Which means from a practical usage perspective it's unlikely for you to get 2 identical timestamps if you're only running a single app.

    If you run multiple processes with multiple updates then this case becomes more likely.