In Mongoose, how can I ensure a field is not returned by default - if that field uses a ref
?
const userSchema = new mongoose.Schema({
// --- Works
isActive: {
type: Boolean,
select: false,
},
// --- Does NOT work
clientsList: [ {
type: mongoose.Schema.Types.ObjectId,
ref: 'Client',
select: false,
}],
});
If I retrieve this user with User.findById
, then the returned User object will not include isActive
(as expected), but will include clientsList
(not expected).
Is there a way to deselect the second field as well?
PS: I understand that I can manually do .select('-clientsList')
at the query level, but would prefer to deselect it add the model level, similar to the first field.
You need to exclude the array itself, you are currently excluding the values inside the array.
To fix it, just change your clientList definition like this:
clientsList: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Client",
select: false
}
],
select: false
}