I defined an instance method on a schema that I can't seem to access. Before I go into details, I'll say that I have read [this question] (Mongoose instance method is undefined), which had the same problem, but my root cause must be different. I defined all instance methods before I connected the model to its name.
First I defined a schema, and then defined an instance method: AccountSchema.methods.addFunds = function(amountToAd, callback) { // do some stuff to add funds return callback(); }
At the bottom of that file, I associate the name to the schema: var exports = module.exports = Account = mongoose.model('Account', AccountSchema);
For the record, just before associating the schema and name, I checked to make sure that AccountSchema.methods had my instance method.
Later, I use Account.findOne to fetch an instance of an account:
AccountSchema.statics.login = function( email, password, callback) {
Account.findOne({ email:email}, function( err, doc){
if(err) {
console.log(err, null);
}
// below is just some stuff to see if the doc is associated to the schema
if(doc) {
var keys = Object.keys(doc.schema);
for(var propertyName in doc.schema) {
console.log(propertyName + ": " + doc[propertyName]);
}
// blah, do some other stuff
callback(doc);
}
}
I include the snippet above because it looks like at the time I fetched the account from my db, it no longer has any instance methods.
Finally, when I try to call doc.addFunds, I get:
TypeError: Object #<Object> has no method 'addFunds'
I'd appreciate any help or a link to a fully complete mongoose schema definition that uses instance methods.
Should it be something like this instead ?
AccountSchema.statics.login = function( email, password, callback) {
Account.findOne({ email:email}, function( err, doc){
if(err) {
console.log(err, null);
}
if(doc) {
var keys = Object.keys(doc.schema);
for(var key in keys) {
console.log(key + ": " + doc.schema[key]); // I changed doc[key] to doc.schema[key]
}
}
callback(doc);
}
});