Exactly Same Query Behaving Differently in Mongo Client and Mongoose

Understanding Mongoose's strict schema handling

You might notice that the same query behaves differently in a MongoDB client, like Compass or mongo shell, compared to when using Mongoose within a Node.js application. Below is one such scenario.

Consider the following document in a MongoDB collection:

{
  "_id": "61376f7d45f6a2b7dcd1a5e2",
  "name": "John Doe",
  "email": "john@example.com",
  "isVerified": true
}

And here’s your User schema in the application:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
      type: String,
      required: true
  },
  email: {
      type: String,
      required: true
  }
  // Note: The `isVerified` field is missing here
});

const User = mongoose.model('User', userSchema);

Now, in any mongodb client you will get all four fields mentioned above on the following query:

db.users.find({ "email": "john@example.com" })

However, if you run a similar query using Mongoose:


const result = await User.find({ "email": "john@example.com" });
console.log(result);

The result will be:

{
  "_id": "61376f7d45f6a2b7dcd1a5e2",
  "name": "John Doe",
  "email": "john@example.com"
}

Notice that isVerified is missing from the result.

The same will happen on add or update query when you try to include a field that is absent from the Mongoose schema. Mongoose will simply ignore that field and persist the remaining fields that are defined in the schema.

The Reason

Mongoose enforces the schema you’ve defined for your models. Any field not present in your Mongoose schema will be ignored during CRUD operations, unless you use lean() on get queries.

While using Mongoose ODM, always ensure that your schema is compatible with your queries to avoid inconsistencies in query/operation results.




See also

When you purchase through links on techighness.com, I may earn an affiliate commission.