I have defined these three models in mongoose:
const clientSchema = new mongoose.Schema({
name: String,
role: String,
age: {
type: Number,
default: 10
}
})
clientSchema.pre('save', function(){
const doc = this
doc.role = 'client'
})
const adminSchema = new mongoose.Schema({
name: String,
role: String,
})
adminSchema.pre('save', function(){
const doc = this
doc.role = 'admin'
})
const userSchema = new mongoose.Schema({
name: String,
role: String,
age: {
type: Number,
default: 10
},
})
const AdminModel = mongoose.model('AdminModel', AdminModel, 'users')
const ClientModel = mongoose.model('ClientModel', ClientModel, 'users')
const UserModel = mongoose.model('UserModel', UserModel, 'users')
and I have the following route in my express app:
app.route('/users').get(async(req, res, next)=>{
const docs = UserModel.find({ role: 'admin' })
})
It works as expected, except that it's returning the following to the client-side:
{
"name": "James Breakers",
"role": "admin",
"age": 10
}
and this is wrong, and it causes many problems.
On write, it works great, it saves it in the database without the age: 10
, but the problem is when retrieving (reading) from the database, Mongoose is setting the field age: 10
.
and All of that is only because I used the UserModel to retrieve that admin. But I don't want that default behavior of Mongoose at all.
How can I disable it? is there a schema option for that?