How do you iterate over Mongoose model properties within a middleware function?
You're using integer indexes instead of the string references from the fields array. It should be:
var fields = Object.keys(this);for(var i = 0; i < fields.length; i++) { console.log(this[fields[i]]);}
(e.g., you were doing this[1]
, this[2]
, instead of this[fields[1]]
)
I found a slightly different way to accomplish what I wanted which was to iterate over the model properties of a Mongoose model within a middleware function. This uses async.js, but you could refactor it to use a generic JS loop or any other control flow library. The key is to get an array of the document's fields, then you can iterate over those and get/set the values using the current context with this
. As far as I know, this will not coerce non-string values into strings. I've tested it with strings, numbers, booleans and objectIds and they are successfully saved as their original data types.
yourSchema.pre('save', function (next) { var self = this; // Get the document's fields var fields = Object.keys(this._doc); // Do whatever you want for each field async.each(fields, function(field, cb) { self[field] = validator.escape(self[field]); cb(); }, function(err){ next(); });});
@JohnnyHK's comment worked for me:
const user = new User();const schemaKeys = Object.keys(user.toObject());