Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Mongoose version
7.1.1
Node.js version
16.x, 18.x
MongoDB server version
4.4
Typescript version (if applicable)
No response
Description
This issue is very similar to this: #13340
7.1.1 is the first version that is bad. I have tested that 7.1.0 works, and that the latest version (7.4.4) also fails.
I have a Schema where one sub-document is not selected by default (select: false
in schema definition). I have queries that needs this sub-document and therefore select it explicitly with the "+" syntax like so: .select("+myField")
.
The problem is that this field is not returned although being explicitly selected.
Note that one difference from #13340 is that now the other fields are included, just not the one that is selected. In #13340 only the _id was returned – no other fields.
Steps to Reproduce
This can be reproduced by running the following code with mongoose >= 7.1.1. See that age is not returned.
If you use mongoose 7.1.0, age is included in the response as expected.
const mongoose = require('mongoose');
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/test');
const kittySchema = new mongoose.Schema({
name: String,
age: {
select: false,
type: Number
}
});
const Kitten = mongoose.model('Kitten', kittySchema);
const silence = new Kitten({ name: 'Silence', age: 2 });
await silence.save()
const updated = await Kitten.findByIdAndUpdate(silence._id, { age: 3 })
.select("+age")
console.log("UPDATED", updated) // <-- Returns _id, name and __v, but not age!
}
main()
Result from the console.log using mongoose 7.1.1:
UPDATED {
_id: new ObjectId("64e674ea250a3fbd6b986c1c"),
name: 'Silence',
__v: 0
}
Result from the console.log using mongoose 7.1.0:
UPDATED {
_id: new ObjectId("64e676bfd40527d1db7d3166"),
name: 'Silence',
age: 2,
__v: 0
}
Expected Behavior
When using .select('+someField')
, someField
should be included in the response.