Wednesday 17 May 2017

mongoose.find() happens after returning an answer to client

I'm trying to make a find() request with mlab. Im using express in my main file (Controller) to route it to the function in my model and over there do the find() from DB. When the app enters this func it probably still didn't connect to the DB so the code inside conn.once isn't running.

so I moved mongooe.connect inside the method and now the client is getting an empty answer. I think the contriller returning an answer before find is finished.

//index.js (the controller)

    const   express     = require('express');
    app         = express(),
    data        = require('./data/securitySettingsDB.json'),
    port        = process.env.PORT || 3000,
    bodyParser  = require('body-parser'),
    methods     = require('./modules');
    var method = methods();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true }));

    app.use(express.static('public'));
    app.get('/', (req,res) => {
        console.log('Trace: API Page');
        res.sendFile(__dirname + '/api/index.html');
    });
    app.get('/getAllUsers/', (req, res) => {
      res.setHeader('Debug', 'getAllUsers was reached');
      res.status(200).json(method.getAllUsers());
    });

    app.listen(port);
    console.log('listening on port ${port}');

//the module

    const consts      = require('../models/consts'),
          mongoose    = require('mongoose');
    var User = require('../models/user');
    class Methods {

      getAllUsers() {
          console.log("Trace : getAllUsers()");
          mongoose.connect(consts.MLAB_KEY);
          conn.on('error', (err) => {
             console.log(`connection error: ${err}`);
          });
          conn.once('open', () => {
             console.log(`once`);
             User.find({}, (err, user) => {
               if(err){
                 console.log(`query error ${err}`);
                 mongoose.disconnect();
               return {"error": err}
               }
               else console.log(`ok`);
               console.log(user);
               mongoose.disconnect();
               return user;
          });
      });
     console.log(`returned from query`);
     }
    module.exports = function() {
    var methods = new Methods();
    return methods;
    }

the Model



via SteveBl

No comments:

Post a Comment