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
- Node JS Mongo Client for Atlas Data API
- SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
- Yup Date Format Validation With Moment JS
- Yup Number Validation: Allow Empty String
- MongoDB Single Update Query to Change the Field Name in All Matching Documents of the Collection
- JavaScript Unit Testing JSON Schema Validation
- AWS Layer: Generate nodejs Zip Layer File Based on the Lambda's Dependencies