Passing reference to DB into routes is not working for my Node / Express project

血红的双手。 提交于 2019-12-04 15:41:27

Your post object is lost as the this in your Post methods when called by the Express route handlers you're registering. You need to bind the methods to your post instance so that no matter how they're called by Express, this will be your post. Like this:

// Set the routes
app.get('/:org/posts', post.find.bind(post));
app.get('/:org/posts/:id', post.get.bind(post));
app.post('/:org/posts', post.add.bind(post));
app.put('/:org/posts/:id', post.update.bind(post));
app.delete('/:org/posts/:id', post.remove.bind(post));

Try this way. It became my favourite way of writing modules since I found this on Stack Overflow some time ago.

server.js:

...    
var Post = require('./routes/posts')(db);
...

posts.js:

...
module.exports =function(db) {
        var module = {};

         module.get = function(req, res){
            ...
            /* db should be accessible here */

         }

         return module;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!