Dima Soroka Dima Soroka - 2 months ago 7
Javascript Question

Why don't work functions in callback?

First function (findOne) is working normal. But all Mongoose function in here callback just don't work without any errors. Why?
Thank you!

var mongoose = require('mongoose');

var Links = require('../models/Links');

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/soft');

Links.findOne({}, function(err, l) {
if (err) throw err;
console.log("1", l);
Links.findOne({}, function(err, l_) {
if (err) throw err;
console.log("2", l_);
});
});

mongoose.connection.close();

Answer

The code is closing the connection before the second .find has a chance to be called. Since .find is async the code executes the first call (which has a connection to execute with) but then continues on and disconnects before the first call returns to execute the second call.

Moving the .close call inside the second call will allow both calls to be made.

var Links = require('../models/Links');

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/soft');

Links.findOne({}, function(err, l) {
  if (err) throw err;
  console.log("1", l);
  Links.findOne({}, function(err, l_) {
    if (err) throw err;
    console.log("2", l_);
    mongoose.connection.close();
  });
});