1

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?

rudox
  • 11
  • 3
  • Related: https://stackoverflow.com/questions/33946972/how-to-split-node-js-files-in-several-files https://stackoverflow.com/questions/19095528/how-to-split-monolithic-node-js-javascript – The Guy with The Hat Sep 14 '18 at 20:40

0 Answers0