J
J
jekmurod2015-07-30 10:19:58
MongoDB
jekmurod, 2015-07-30 10:19:58

MongoDB and NodeJs?

for some reason, the function writes undefined to me, maybe the function did it wrong, but did it?

function checkUserIdentity(lg) {
  MongoClient.connect('mongodb://адрес', function (err, db) {
    if (err)
      throw err;
    var collection = db
      .collection('client')
      .findOne({
        login : lg
      }, function (err, docs) {
        if (docs) {
          return docs._id;
        }else {
          return "not exist";
        }
      })
  });
}

when i do console.log(checkUserIdentity("")) // response is undefined
but when i do like this without function
MongoClient.connect('mongodb://адрес', function (err, db) {
    if (err)
      throw err;
    var collection = db
      .collection('client')
      .findOne({
        login : lg
      }, function (err, docs) {
        if (docs) {
          return docs._id;
        }else {
          return "not exist";
        }
      })
  });

everything is in order for some reason the function does not return
what could be the problem ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2015-07-30
@jekmurod

function checkUserIdentity(lg, callback) {
  MongoClient.connect('mongodb://адрес', function (err, db) {
    if (err) throw err;
    db.collection('client').findOne({ login : lg }, function (err, docs) {
      if (docs) callback(null, docs._id);
      else callback(new Error("not exists"));
    });
  });
}

T
tex0, 2015-07-30
@tex0

when i do console.log(checkUserIdentity("")) // response is undefined

Well, firstly, your function itself does not return anything. Therefore, undefined.
Secondly, I suspect that return in the callback function is useless because the host function (MongoClient.connect) does not provide for receiving data from the callback through the return statement. And thirdly, all this (except for your self-written function) works in asynchronous mode. Those. control in f-yu checkUserIdentity is transferred immediately after the call to MongoClient.connect and you will receive the result of the connection is unknown when.
Change your approach to architecture. Start thinking asynchronously =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question