MongoDB Atlas and mongoose model

Hello, I’m following one of youtube tutorials about passport validation with node.js. I had connected to my MongoDB Atlas cluster. Then I createed schema and model based on it called User.
When the user is registering I want to check if there is already existing user with that email in database. The guy in the tutorial used User.findOne({email: email});
My question is, why is he looking for that user in model, not in the database? Does the model after we created it, is ‘reflection’ of the collection in MongoDB Atlas cloud?

Hello!

Sort of.

A model in mongoose, is the interface that allows you to operate on a specific collection. It’s an interface to the underlying mongodb driver.

The same could be accomplished using the MongoDB driver:

async function findUserByEmail(email) {
  try {
    const user = await db.collection("user")
                 .findOne({ email: email });
    return user;
  } catch (e) {
    console.error(`Could not find the user ${email}: ${e}`);
  }
  return null;
}

Think of a model as a convenience to interacting with the database (that’s an interface, actually :stuck_out_tongue:).

1 Like