node app:在mongoose db setup之后设置路由?

时间:2015-08-08 21:32:01

标签: node.js mongodb express mongoose

我目前正在开发一个网络应用。我刚刚开始开发,我尝试在db(mongoose Schemas和连接)准备好之后设置路由,因为我需要router.js文件中的模型。我的代码现在看起来像这样:



File: server.js

//configuration here...

mongoose.connect( "mongodb://" + config.database.host + "/" + config.database.dbName );
var db = mongoose.connection;
db.on( "error", console.error.bind(console, "connection error:" ));
db.once( "open", function () {
    var allModels = models.getAll( mongoose ); //retreive models from different files
    router.setupRoutes(express, app, allModels); //setup all the routes  also specified in other files
    console.log("connected to database and created the routes!");
});


app.listen(port, host, function() {
    console.log("");
    console.log("Server started at: " + "http://" + host + ":" + port);
    console.log("Press 'STRG+C' to stop the Server");
    console.log("");
});




我的问题是: 这是正确的方法吗?我将app.listen函数称为不在此一次(" open")函数中(app.listen位于此文件的底部并在设置路由之前调用)我的测试路由正在运行但我即时通讯现在没有访问猫鼬模型。我应该在mongoose回调中调用app.listen还是现在在我的文件末尾调用?

我只是想确保这是正确的方法。这似乎是正确的方式。 mongoose这么说...... Look here

2 个答案:

答案 0 :(得分:0)

我不会说有正确或错误的方式。这取决于你想要做什么。以下是我的想法:

如果数据库连接不起作用,是否要让服务器运行?也许是因为有些路线不涉及数据库?如果这是你的目标,你必须在数据库连接回调之外设置路由。像这样:

db.once('open', function() {
  // set up routes that involve db connection
});

// set up routes that don't involve db connection
app.listen(port, host, function() {
});

如果所有路由都涉及数据库通信,我看不到在数据库连接回调之外使用app.listen的目的。因为如果数据库连接中断,服务器正在侦听这一事实将无用。

答案 1 :(得分:0)

我想指出具体情况。当我们将连接放入server.js时,应用程序将在午餐时尝试连接。如果发生错误,它将抛出错误,并且永远不会回头。但是,当我们将连接放在路由中时,应用程序将尝试仅在需要时以及每次需要时才到达db。这使我们能够到达与db相关的端点而没有相关的端点,并且打开数据库状态更改。因此,如果数据库有问题并且我们已解决,则无需重新启动服务器。

相关问题