I'm using version 3.8.19.
Code:
var UserSchema = new mongoose.Schema({
username: {
type: String,
}
});
UserSchema.virtual('username').get(function() {
return this.username;
}).set(function(username) {
this.usernameLower = username.toLowerCase();
});
Error:
/project/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:296
throw err;
^
TypeError: Object #<Object> has no method 'get'
at Object.<anonymous> (/project/models/user.js:115:32)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
Hello!
I think that you can't assign a getter, because first you defininig a real property in your schema and then trying to redeclare it as a virtual.
So the solution is to change either a name of a virtual property or an object's property.
var UserSchema = new mongoose.Schema({
username: {
type: String,
}
});
UserSchema.virtual('usernameLower').get(function() {
return this.username.toLowerCase();
}).set(function(usernameLower) {
this.username = usernameLower;
});
or
var UserSchema = new mongoose.Schema({
usernameLower: {
type: String,
}
});
UserSchema.virtual('username').get(function() {
return this.usernameLower;
}).set(function(username) {
this.usernameLower = username.toLowerCase();
});
@k10der is correct
What is the correct way to override a setter or getter with mongoose, and to make sure that method is used?
Hi, eytanbiala.
If you need a custom getter(setter) for your schema field, you need just need to define a getter(setter) function for the path:
http://mongoosejs.com/docs/api.html#schematype_SchemaType-get
http://mongoosejs.com/docs/api.html#schematype_SchemaType-set
For example:
var UserSchema = new mongoose.Schema({
username: {
type: String,
}
});
UserSchema.path('username')
.get(function(value) {
return value;
})
.set(function(value) {
return value.toLowerCase();
});
Thanks!
Thank you @k10der, great answer!
Would be great if @k10der's answer was in the docs here: http://mongoosejs.com/docs/guide.html
I had the same problem. I wanted to update a date when a specific field in my schema changed. Made the same mistake by making a virtual that had the same name as the schema property.
Most helpful comment
Hi, eytanbiala.
If you need a custom getter(setter) for your schema field, you need just need to define a getter(setter) function for the path:
http://mongoosejs.com/docs/api.html#schematype_SchemaType-get
http://mongoosejs.com/docs/api.html#schematype_SchemaType-set
For example: