Advanced Node.js Development
上QQ阅读APP看书,第一时间看更新

Refactoring the server.js file to create POST todos route

To get started, inside of the server folder, we're going to make a new folder called db, and inside of the db folder we'll make a file where all of this Mongoose configuration will happen. I'm going to call that file mongoose.js, and all we need to do is take our Mongoose configuration code right here:

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/TodoApp');

Cut it out, and to move it over into mongoose.js. Now, we need to export something. What we're going to export is the mongoose variable. So essentially, when someone requires the mongoose.js file, they're going to have Mongoose configured and they're going to get it —they're going to get back the mongoose variable that comes from the library. I'm going to set module.exports equal to an object, and on that object we'll set mongoose equal to mongoose:

mongoose.connect('mongodb://localhost:27017/TodoApp');

module.exports = { mongoose: mongoose };

Now as we know, in ES6, this can be simplified. If you have a property and a variable with the same name you can shorten it, and we can take things a step further and put it all on one line:

module.exports = {mongoose};

Now we have the Mongoose configuration in a separate file, and that file can be required in the server.js file. I'm going to pull off the mongoose property using ES6 destructuring. Essentially, we're creating a local variable called mongoose equal to the mongoose property on the object, and that object is going to be the return result from requiring the file we just created. It's in the db directory and it's called mongoose.js, and we can leave off that extension:

var mongoose = require('./db/mongoose');

Now that Mongoose lives in its own place, let's do the same thing for Todo and User. This is going to happen in a new folder in a server called models.