Solved: I can only guess that delirium got me.
sorry for not figuring it out before posting, but here's the solution for the next persons sake. The try/catch is not necessary, but it did help me get out some errors that were not being printed to console. If there is a better way to document solving my own problem, I'd appreciate the feedback.
Old Question
I have docs stored in my mongo db that I want to modify before being returned to a find() or findOne(). I want to do this without changing the values and a single hook for all find variants. Call it a masking. I'm actually normalizing a numeric value to a scale of 0 to 1. I do not want to modify the value in the doc, just change the values when the doc is returned via find, findOne. E.G. "Change Model values after load in Mongoose"
Solution
schema.post('init', function(doc){
try{
console.log(doc); // prints the doc to console, complete
doc.property = "new property value"; // changes the document value
console.log(doc); // returns the modified document
return doc;
}
catch(error){
console.log(error);
}
}
Old Notes
Other threads note usage of the post init hook. I have tried the methods in the following related topics with no success.
Mongoose - how to tap schema middleware into the 'init' event?
Change Model values after load in Mongoose (this method has changed with 5.x)
schema.post('init', function(doc){
console.log('Tell me i fired'); // works, prints to console
console.log(doc); // works, prints full model to console
doc.valueField = doc.valueField2+doc.valueField3; // fails, no doc returned, throws no errors
});
schema.post('init', function(doc, next){
console.log('Tell me i fired'); // works, prints to console
console.log(doc); // works, prints full model to console
doc.valueField1 = doc.valueField2+doc.valueField3; // fails, no doc returned, throws no errors
next();
});
I've tried adding return(doc);, doc.save() and just about every mutation of the above code I can compile in my shrinking mental capacity. I keep throwing crap at the wall and nothing is sticking. The documentation over at mongoose is poor and the behavior changed with version 5.x with the removal of Asynch call backs (dropped the next() ).
This is a bug submission on mongoose where the dropping of next() is noted. https://github.com/Automattic/mongoose/issues/6037
release notes from the 5.x release https://github.com/Automattic/mongoose/blob/master/migrating_to_5.md#init-hook-signatures
~ Edited, because i solved my own problem ~