Username does not work for custom mongodb connection

I have a customer mongodb connection. The connection successfully creates users in my mongodb cluster with create user and with require username, however when I attempt to login, I receive a profile not defined error if I sign in with username instead of email. When I use email instead of username the correct user is found.
The only edition I’ve made to login or get user is to add my custom mongo db connection url. I haven’t altered the actual code at all for those scripts?
I asked this question previously and did not figure out a solution,
I am happy to send my account details for someone to take a closer look but please help me get this resolved I’ve been struggling with this,

Here is what the getUser custom function template for mongodb looks like, how should I alter this to get the user based on username?

function getByEmail(email, callback) {
const MongoClient = require(‘mongodb@3.1.4’).MongoClient;
const client = new MongoClient(‘mongodb+srv://mern:’+configuration.MONGO_PASSWORD+’’);

client.connect(function (err) {
if (err) return callback(err);

const db = client.db('test');
const users = db.collection('users');

users.findOne({ email: email }, function (err, user) {

  if (err) return callback(err);
  if (!user) return callback(null, null);

  return callback(null, {
    user_id: user._id.toString(),
    nickname: user.nickname,


Hi @raalrwai ,

The sample template is assuming you are using emails only, not usernames.

When you enable “Requires Username”, you will need to add additional logic to your Custom DB scripts to be able to handle the email parameter being passed as either an email or a username, and be able to find the user correctly with either. In both cases, it should return the same profile, including the username in said profile so it can be stored in Auth0 (for import mode).

This is mentioned in the docs:

The email address for the user as the user identifying credential. If Requires Username is enabled for your connection, the Get User script may run multiple times for some transactions (ex. Creating a user, or requesting a password reset link). In these cases the value of the parameter will sometimes be a username instead of an email. Your code should be able to handle either value and always return the same profile for a given user regardless of whether they were looked up by email or username.

You may find using an $or operator to carry out the search for the “email” parameter in email or username useful if either can be used in your use case:

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.