【问题标题】:How to enable console logging for MongoDB errors?如何为 MongoDB 错误启用控制台日志记录?
【发布时间】:2020-07-12 03:00:26
【问题描述】:

我正在开发一个 NodeJS 应用程序。我在将对象保存到数据库时遇到问题;我控制器中的代码是:

console.log("Before save: " + transaction);
transaction = await transaction.save();
console.log("After save");

在运行Node应用程序的终端中,我看到了:

保存前:{ _ID: ..., 创建:..., ... }

仅此而已,而浏览器页面看起来正在加载。

我尝试将其包装在 try-catch 块中:

try {
  transaction = await transaction.save();
} catch (err) {
  console.log(err);
}

我在终端中得到相同的输出。我想,由于没有 try-catch,我在控制台中看不到错误,所以我也看不到它。

一个问题是该对象的 MongoDB 集合不存在(我问过它here)。但我还有另一个错误。

当我在开发过程中,如何让 MongoDB 在运行 NodeJS 的终端中显示这些错误(缺少集合,以及我仍在寻找的错误)?

【问题讨论】:

  • 你可以使用try-catch;将可能引发错误的代码放在 try 块中。见try-catch with NodeJSMongoDB docs with try-catch examples
  • @prasad_ 我确实尝试过,但忘了把它放在问题中。我现在加了。
  • “我发现一个问题是该对象的 MongoDB 集合不存在。” 您的意思是该集合在数据库中不存在,您正在尝试查询它?这不是错误。
  • @prasad_ 很抱歉造成混乱,我现在说得更清楚了。这是不存在的集合。我还有一个错误。
  • @miguelmorin 对于“安全:真”,您必须将其作为第二个参数传递给 Schema 定义的对象。来源:mongoosejs.com/docs/2.7.x/docs/schema-options.html

标签: node.js mongodb logging


【解决方案1】:

我发现了问题:我在预保存挂钩中省略了next();

SomeSchema.pre('save', function(next) {
  // any logic you require
  if (this.condition) {
    // ...
  }
  next();  // <- this is required, else Mongo won't save nor return
});

所以我没有收到错误,因为没有错误,只是调用流程中断。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多