I
I
Ivan-P2017-04-04 15:29:43
Node.js
Ivan-P, 2017-04-04 15:29:43

How to break nodejs into modules and pass values ​​to them when require?

I am writing a simple REST API on Nodejs - everything is in one file so far. I decided to move the bans to files under the headings:
tasks.js file

module.exports = function(app, db) {

  app.get('/tasks', (req, res) => {
    let findParams = {};

    if (req.query.category) {
      findParams.category = {};
      findParams.category.$in = req.query.category.split(' ');
    }

    if (req.query.importance) {
      findParams.importance = {};
      findParams.importance.$in = req.query.importance.split(' ');
    }

    if (req.query.cost) {
      findParams.cost = {};
      let cost = req.query.cost.split(' ');
      if (cost.indexOf('free') != -1 && cost.indexOf('paid') == -1) {
        findParams.cost.$eq = 0;
      }

      if (cost.indexOf('free') == -1 && cost.indexOf('paid') != -1) {
        findParams.cost.$gt = 0;
      }

      if (cost.indexOf('free') != -1 && cost.indexOf('paid') != -1) {
        findParams.cost.$gte = 0;
      }

    }

    // if (err) throw err;
    db.collection('tasks').find(findParams).toArray((err, results) => {
      res.send(results);
    });

  });

};

Main index.js file:
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cors());

var db;

MongoClient.connect('mongodb://xxxxxxxxxxxxxxxxxxxxx/swq', (err, database) => {

  if (err) {
    return console.log(err);
  };

  db = database;

  app.set('port', (process.env.PORT || 3000));

  app.listen(app.get('port'), function () {
    console.log('Node app is running on port', app.get('port'));
  });
});
require('./tasks')(app, db);

But I get TypeError: Cannot read property 'collection' of undefined.
How to transfer db?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question