-
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 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? The question is also posted on StackOverflow as well |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
Beta Was this translation helpful? Give feedback.
const docs = await UserModel.find({ role: 'admin' }).setOptions({ defaults: false })
in Mongoose >= 5.12.10, see #7287