[Mongoose] Saving Error Objects to Schema.Types.Mixed Fields
Tadashi Shigeoka · Tue, May 16, 2017
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.
Sample Code for Saving Errors to Schema.Types.Mixed
(Example) Sample Code That Failed to Save Error Directly
var err = new Error('bad');
Model.updateOne({
_id: targetId
}, {
'mixedField': err ? err.toString() : null
}, function(updatedErr) {
});
(Example) Sample Code That Saved Error Using toString
var err = new Error('good');
Model.updateOne({
_id: targetId
}, {
'mixedField': err ? err.toString() : null
}, function(updatedErr) {
});
(Example) Sample Code That Saved Error Using lodash.toPlainObject
const _ = require('lodash');
var err = new Error('good');
Model.updateOne({
_id: targetId
}, {
'mixedField': err ? _.toPlainObject(err) : null
}, function(updatedErr) {
});
Summary
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.
Reference Information
- Mongoose SchemaTypes
- Errors | Node.js Documentation
- Object.prototype.toString() - JavaScript | MDN
- Lodash Documentation
That’s all from the Gemba.