Node.js:在被调用脚本中访问db

时间:2016-01-02 22:25:38

标签: javascript node.js heroku

我有一个每10分钟运行一次的heroku调度程序作业,并调用expiration.js文件。此文件位于app.js旁边的根文件夹中。

expiration.js:

var app = require('./app.js');

function checkForExpiration() {
  var db = app.get('db');
  var collection = db.collection('postingcollection');
  // do stuff with collection that checks for expiration
}
checkForExpiration();

在我的app.js文件中我有:

app = express();
//setup db with mongolab
app.set('db', db);
module.exports = app; 

您可能认为我没有正确设置我的数据库,但它可以在我的路由中的其他地方工作。我只是无法在此执行的文件中访问它。运行文件时,我看到此错误:

2016-01-02T22:09:27.924443+00:00 heroku[api]: Starting process with command `node expiration` by scheduler@addons.heroku.com
2016-01-02T22:09:32.028186+00:00 heroku[scheduler.5884]: Starting process with command `node expiration`
2016-01-02T22:09:32.700417+00:00 heroku[scheduler.5884]: State changed from starting to up
2016-01-02T22:09:34.312517+00:00 app[scheduler.5884]: Failed to load c++ bson extension, using pure JS version
2016-01-02T22:09:35.154509+00:00 app[scheduler.5884]: /app/expiration.js:6
2016-01-02T22:09:35.154513+00:00 app[scheduler.5884]:   var collection = db.collection('postingcollection');
2016-01-02T22:09:35.154514+00:00 app[scheduler.5884]:                      ^
2016-01-02T22:09:35.154515+00:00 app[scheduler.5884]:
2016-01-02T22:09:35.154516+00:00 app[scheduler.5884]: TypeError: Cannot read property 'collection' of undefined
2016-01-02T22:09:35.154516+00:00 app[scheduler.5884]:   at checkForExpiration (/app/expiration.js:6:22)
2016-01-02T22:09:35.154517+00:00 app[scheduler.5884]:   at Object.<anonymous> (/app/expiration.js:52:1)
2016-01-02T22:09:35.154518+00:00 app[scheduler.5884]:   at Module._compile (module.js:425:26)
2016-01-02T22:09:35.154519+00:00 app[scheduler.5884]:   at Object.Module._extensions..js (module.js:432:10)
2016-01-02T22:09:35.154520+00:00 app[scheduler.5884]:   at Module.load (module.js:356:32)
2016-01-02T22:09:35.154521+00:00 app[scheduler.5884]:   at Function.Module._load (module.js:313:12)
2016-01-02T22:09:35.154521+00:00 app[scheduler.5884]:   at Function.Module.runMain (module.js:457:10)
2016-01-02T22:09:35.154522+00:00 app[scheduler.5884]:   at startup (node.js:138:18)
2016-01-02T22:09:35.154523+00:00 app[scheduler.5884]:   at node.js:974:3

看起来var db是未定义的,因此不是数据库。

我的问题是如何在此可执行脚本中访问我的应用程序数据库?

1 个答案:

答案 0 :(得分:0)

app.set can only be used for internal settings.

您可以使用app.locals.db或仅设置app.db