0
我目前正在开发一个网络应用程序。我刚开始开发,我尝试在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函数不在这里一次(“打开”)函数(app.listen位于此文件的底部,并在设置路由之前调用)我的测试路线正在工作,但我没有访问猫鼬模型马上。我应该在mongoose回调中调用app.listen还是现在在我的文件末尾?
我只是想确保这是做到这一点的正确方法。它似乎是正确的方式。猫鼬这么说... Look here
thx为您的答案。我现在也在回调中调用app.listen,因为如果服务器启动了,但数据库还没有设置,那么对我的应用程序来说就没有意义了。 – Wolfgaung