node.js & express - global modules & best practices for application structure

后端 未结 3 1458
醉话见心
醉话见心 2020-12-23 12:57

I\'m building a node.js app that is a REST api using express and mongoose for my mongodb. I\'ve got the CRUD endpoints all setup now, but I was just wondering two things.

3条回答
  •  Happy的楠姐
    2020-12-23 13:09

    I found this StackOverflow post very helpful:

    File Structure of Mongoose & NodeJS Project

    The trick is to put your schema into models directory. Then, in any route, you can require('../models').whatever.

    Also, I generally start the mongoose db connection in app.js, and only start the Express server once the connection is up:

    mongoose.connect('mongodb://localhost/whateverdb')
    mongoose.connection.on('error', function(err) {
      console.log("Error while connecting to MongoDB:  " + err);
      process.exit();
    });
    mongoose.connection.on('connected', function(err) {
      console.log('mongoose is now connected');
      // start app here
      http.createServer(app).listen(app.get('port'), function(){
        console.log('Express server listening on port ' + app.get('port'));
      });
    
    });
    

提交回复
热议问题