What should the NodeJS driver (4.x) `findOne()` return if no match is found?

As the topic title suggests, I’m trying to ascertain what should be returned if findOne doesn’t get a match.

I did not see this scenario in the documentation.

From my coding test, it appears to be undefined. Based on the mflix code base, getUser(), I thought perhaps an error was supposed to be thrown:

  static async getUser(email) {
    // TODO Ticket: User Management
    // Retrieve the user document corresponding with the user's email.
    try {
      return await users.findOne({ email: email })
    } catch (e) {
      console.error(`Unable to find user with email ${email}` );
      return null
    }
  }

In my own code, when I run a test against this using an email not in the database, an error is not thrown and instead undefined is returned to the calling function.

Did something change in the latest releases?

2 Likes

Hello @Tim_Rohrer, I think that is the expected behavior. With NodeJS driver version 4.0, the Collection#findOne returns an undefined when no match is found. In the earlier driver version 3.6 the same method returned a null.

Also, when no document is found it is not an error.

If you run the same query in the mongo shell the method returns a null, in case there is no match.

2 Likes

Thank you. That makes sense but I didn’t see anything in the docs.

I’ll rework the code to handle the undefined condition.

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