Code from official site:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));
I would like to separate the code into separate files:
/models/cat.js
/db.js
/index.js
In db.js:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
module.exports = mongoose;
In models/cat.js:
const mongoose = require('mongoose');
const Cat = mongoose.model('Cat', { name: String });
module.exports = Cat;
And in index.js:
const Cat = require('./models/cat');
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));
index.js is the starting file for my application, but I do not require the db.js file to it, because I don't know what for... index.js doesn't use constant mongoose, so how can I make the whole application use my connection from the db.js file?