MongoDB schema design for multiple auth user accounts

1) There are three strategies that you might take to structure your data in MongoDB:

  • a) Array of embedded documents
  • b) Array of embedded references
  • c) Expanded into the parent document

Strategy (a) is the first one you describe, where the Profile document contains an array of Account sub-documents.

Strategy (b) is similar to strategy (a), but you’d use an array of references to other documents (typically in an Account collection) rather than embedding the actual documents.

Strategy (c) is the one you describe as “having all data in a single model”.

2) It’s generally considered Best Practice to use an array of embedded documents, especially if the information in them can vary. If it will make your life easier, you can use a key to distinguish the type of the account, like so:

  { 
    firstname: 'Fred',
    lastname: 'Rogers',
    email: 'fred.rogers@example.com',

    accounts: [
             { kind: 'facebook',
               uid: 'fred.rogers'
             },
             { kind: 'internal',
               username: 'frogers',
               password: '5d41402abc4b2a76b9719d911017c592'
             },
             { kind: 'twitter',
               uid: 'fredr'
             }
          ]
    }

3) MongoDB allows you search on an embedded document. So you would write the following query (JavaScript syntax):

 db.profile.find( 
        { email: 'fred.rogers@example.com', 'accounts.kind': 'facebook' }
        );

With appropriate indexes, this query will be quite fast.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)