5

Let's say we have an error object like this:

const error = new Error('Error');

How can I store this in mongo? Tried to store it in a field with the type Object (Even tried the type Mixed) but it just stores an empty Object.

const UserLogSchema = new Schema(
  {
    ...
    error: {
      type: Schema.Types.Mixed
    }
  },
  {
    timestamps: true
  }
);

const UserLog = mongoose.model('UserLog', UserLogSchema);

Adding the error:

const userLog = await UserLog.findOne({ _id: userLogID });

userLog.error = new Error('Error');

await userLog.save();

When we try to get the error later:

const userLog = await UserLog.findOne({ _id: userLogID });

console.log(userLog.error)

It just prints {}. But the actual error is not empty.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
THpubs
  • 7,804
  • 16
  • 68
  • 143

2 Answers2

6

Is it sufficient solution to serialize the error object and store as a json string?

error = new Error('ahhhh');
errorJson = JSON.stringify(error, Object.getOwnPropertyNames(error));
console.log(errorJson);
// output: {"stack":"Error: ahhhh\n    at <anonymous>:1:7","message":"ahhhh"}

See similar question here, you could also use serialize-error package.

joshweir
  • 5,427
  • 3
  • 39
  • 59
0

All you need is to create a schema in mongoose for storing error with two properties like

{
  errorDescription: {
    type: 'object',
    required: true
  },
  timestamp: {}
}

something like this, and whenever you got an error access this scema and save it it the DB schemaName.save('errroObject',function(obj){}). This will save you information.

joshweir
  • 5,427
  • 3
  • 39
  • 59
Mr. Raj Kale
  • 87
  • 1
  • 1
  • 7