angularjs - MEAN Stack Error when calling two different api's routes at the same time -
having issues angularjs, mongoose or mongolab. if make 2 api calls different api route @ same time, data won't load. got working waiting each call finish (with promise) before making next call. way me doesn't sound me because if of call fail, rest of page won't load. there anyway can avoid waiting? here example of got right now.
angularjs controllers working code:
// profiles homeservices.getprofile() .then(function (result) { $scope.profiles = result.data; // portfolios homeservices.getportfolios() .then(function (result) { $scope.portfolios = result.data; }, function (error) { console.log(error.statustext); }); }, function (error) { console.log(error.statustext); });
api's:
// profile api api.get('/profiles', function (req, res) { // model schema var profile = require('../models/profile'); // create db connection var db = mongoose.createconnection(config.server.db); // set model var model = db.model('profile', profile, 'profiles'); // find videos model.find({}, function (err, data) { if (err) { res.status(500).send(err); } else { res.status(200).send(data); } // disconnect db mongoose.disconnect(); }); }); // portfolio api api.get('/portfolios', function (req, res) { // model schema var portfolio = require('../models/portfolio'); // create db connection var db = mongoose.createconnection(config.server.db); // set model var model = db.model('portfolio', portfolio, 'portfolios'); // find videos model.find({}, function (err, data) { if (err) { console.log(err); res.status(500).send(err); } else { res.status(200).send(data); } // disconnect db mongoose.disconnect(); }); });
here want able do:
// profiles homeservices.getprofile() .then(function (result) { $scope.profiles = result.data; }, function (error) { console.log(error.statustext); }); // portfolios homeservices.getportfolios() .then(function (result) { $scope.portfolios = result.data; }, function (error) { console.log(error.statustext); });
here error mongolab:
{ [mongoerror: server mongolab.com:59661 sockets closed] name: 'mongoerror', message: 'server db... sockets closed' }
update: removing mongoose.disconnect(); works needed. don't want create connection @ each endpoint.
i believe error comes constant create/close of mongo connection. sustain single connection on multiple endpoints:
var portfolio = require("../models/portfolio") var profile = require("../models/profile") var db = mongoose.connect(config.server.db) db.connection.once("connected", function() { api.get("/profiles", function(req, res) { ... }); api.get("/portfolios", function(req, res) { ... }); });
you using createconnection()
used creating connections multiple databases. judging these endpoints, don't need that. i'd use connect()
instead. recommend reading more connections here
as aside, defined portfolio , profile @ top of file, since may repeated on different endpoints.
Comments
Post a Comment