Search code examples
pythonmongodbaccess-token

Storing access tokens in the user's collection is better or separate?


I am using mongodb with python and trying to figure out how should I store the access tokens, whether I should go with embedded documents and store access tokens in the same user's collection or create a new collection called access_tokens and keep a reference field of user in that?

Here's the example with different collection:

{
    "_id" : ObjectId("5b8bc5efac5a49b53fddb4d6"),
    "name" : "Rohit Khatri",
    "email" : "rohit@email.com",
    "username" : "rohit",
    "password" : "password"
}

{
    "_id" : ObjectId("5b8bdc2aac5a49b82c1f4e32"),
    "token" : "sf33849hskjdfhj9348khsjdf",
    "expires_at" : ISODate("2018-09-02T12:48:42.218Z"),
    "user_id" : {
        "$ref" : "users",
        "$id" : ObjectId("5b8bc5efac5a49b53fddb4d6")
    }
}

With embedded collection

{
    "_id" : ObjectId("5b8bc5efac5a49b53fddb4d6"),
    "name" : "Rohit Khatri",
    "email" : "rohit@email.com",
    "username" : "rohit",
    "password" : "password",
    "access_tokens": [
        {
            "token" : "sf33849hskjdfhj9348khsjdf",
            "expires_at" : ISODate("2018-09-02T12:48:42.218Z")
        }
    ]
}

Which way is better in terms of performance, scalability, etc.?


Solution

  • One nice side effect of keeping the tokens in a separate collection is that you could use a TTL index on that collection to automatically delete older token records. The index isn’t guaranteed to run exactly at the time you have set in your expires_at field but it would be very close to that time if accuracy in seconds isn’t important to you. That way all you’d need to check is if the token exists and not whether it’s expired.