假设我们有一个这样的错误对象:
const error = new Error('Error');
如何将其存储在 mongo 中?试图将它存储在一个对象类型的字段中(甚至尝试了混合类型)但它只存储了一个空对象。
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)
它只打印 {}
。但实际错误并不为空。
最佳答案
序列化错误对象并存储为 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包。
关于javascript - 如何用 mongoose 存储 javascript 错误对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49870976/