[Mongoose] Saving Error Objects to Schema.Types.Mixed Fields
I couldn’t save Node.js Error objects directly to Mongoose Schema.Types.Mixed fields, so I had to use toString() or _.toPlainObject() before saving them.
var err = new Error('bad');
Model.updateOne({
_id: targetId
}, {
'mixedField': err ? err.toString() : null
}, function(updatedErr) {
});
var err = new Error('good');
Model.updateOne({
_id: targetId
}, {
'mixedField': err ? err.toString() : null
}, function(updatedErr) {
});
const _ = require('lodash');
var err = new Error('good');
Model.updateOne({
_id: targetId
}, {
'mixedField': err ? _.toPlainObject(err) : null
}, function(updatedErr) {
});
I was puzzled because Error objects weren’t being saved to MongoDB, but after changing MongoDB’s LogLevel settings and checking, I found that no values were being passed to the update method in the first place.
I thought Schema.Types.Mixed fields could save anything, but it seems the Mongoose layer doesn’t cast Error objects and instead processes them as saving nothing.
I haven’t read through Mongoose’s source code yet, so I’d like to look into it later.
That’s all from the Gemba.