如何使用mongoose存储javascript错误对象?

时间:2018-04-17 06:06:47

标签: javascript mongodb mongoose

假设我们有一个像这样的错误对象:

const error = new Error('Error');

如何将其存储在mongo中?试图将它存储在Object类型的字段中(甚至尝试了类型Mixed),但它只存储一个空的Object。

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

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

添加错误:

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

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

await userLog.save();

当我们稍后尝试收到错误时:

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

console.log(userLog.error)

它只打印{}。但实际错误并非空白。

2 个答案:

答案 0 :(得分:2)

序列化错误对象并存储为json字符串是否足够?

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"}

查看类似问题here,您也可以使用serialize-error包。

答案 1 :(得分:0)

您只需要在mongoose中创建一个模式,以便使用两个属性(如

)存储错误
{
  errorDescription:{
                    type:'object',
                    required:true
                      },
 timestamp:{}
}

这样的事情,每当你有错误访问这个scema并将它保存到数据库schemaName.save('errroObject',function(obj){})。这将为您节省信息。