【发布时间】:2015-12-03 19:03:24
【问题描述】:
我正在使用 Node.js 编写在服务器上运行的系统脚本。由于 Node 的异步特性,我的脚本在数据库调用有机会完成之前退出,并且没有任何内容写入数据库。
我使用 Mongoose 作为 ORM 并与 MongoDB 交谈,如果这有什么不同的话。 Node.js 提供 SYNCHRONOUS 方法调用正是出于这个原因,例如:https://nodejs.org/api/child_process.html
我想我的问题是:
1) mongoose 是否提供了一种阻止方法,以便我的脚本进程可以等待数据库调用返回?
2)如果没有,除了类似的方法之外,我还应该考虑其他方法吗:
(function wait () {
if (!SOME_EXIT_CONDITION) setTimeout(wait, 1000);
})();
3) node 不是编写脚本的最佳工具吗?我喜欢用于 web 应用程序开发的 node,并且可以整天编写嵌套回调或使用 Promise。但是作为一种脚本语言呢?
编辑 ---------------------------------- -
下面是一个快速的脚本示例,可以更清楚地说明情况:
#!/usr/bin/env node
# Please note the above that this is a bash script
var schema = mongoose.Schema({
// ... attributes ...
});
var model = new (mongoose.model('ModelObject'))();
model['attribute'] = 42;
console.log('This gets printed first');
model.save(function(err) {
console.log('Nothing in the callback gets printed because callback is never called');
if(err) { // Can't check for errors because this is never reached
console.log('This never gets printed to the screen');
console.log('And consequently nothing is ever saved to mongo');
} else {
console.log('This never gets printed either');
}
});
console.log('This gets printed second');
【问题讨论】:
-
不清楚您的问题是什么。 “我的脚本在数据库调用有机会完成之前退出”你能详细说明一下吗?分享产生问题的代码并详细描述。
-
你描述的方法很好,是什么阻止你使用它?
-
也许保存方法正在引发错误,而您没有捕捉/显示它
-
数据库连接在哪里??
-
这个问题可能是由于Mongo连接处理不当造成的。检查这个stackoverflow.com/questions/10156623/…
标签: javascript node.js mongodb asynchronous mongoose