D
D
Dvorak2016-06-29 11:46:09
MongoDB
Dvorak, 2016-06-29 11:46:09

How to write a function to get a user?

Hello. I want to write a function that takes a database, a user id, a collection and returns the user as an object. Due to the asynchrony of the node, nothing happens. How to fix?

function getUser(db, id, collection) {
  let a;
  db.open(function(err, db) {
    if (err) throw err;
    let users = db.collection(collection);
      let cursor = users.find({telegramId:id});
      a = cursor;
        cursor.toArray(function(err, results) {
          if (err) throw err;
          db.close();
        });
  });

  return a;
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Wolf, 2016-06-29
@mannaro

Since you are already using ES6 (let), then use promises:

function proxy(fn, ...args) {
  return new Promise((res, rej) => {
    fn(...args, (err, result) => {
      if (err) rej(err);
      else res(result);
    });
  });
}

function getUser(db, id, name) {
  var _db;

  var result = proxy(db.open.bind(db)).then(db => {
    _db = db;
    var collection = db.collection(name);
    var cursor = collection.find({
      telegramId: id
    });
    return proxy(cursor.toArray.bind(cursor))
  }).catch(err => {
    console.error(err);
    _db.close();
  });

  result.then(() => _db.close());

  return result;
}

getUser(db, 'user-1', 'users').then(arr => {
  console.log('users: ', arr);
});

Then you can further convert this to generators:
// подключаем npm-библиотеку co
var co = require('co');

function proxy(fn, ...args) {
  return new Promise((res, rej) => {
    fn(...args, (err, result) => {
      if (err) rej(err);
      else res(result);
    });
  });
}

function getUser(db, id, name) {
  var _db;

  var result = proxy(db.open.bind(db)).then(db => {
    _db = db;
    var collection = db.collection(name);
    var cursor = collection.find({
      telegramId: id
    });
    return proxy(cursor.toArray.bind(cursor))
  }).catch(err => {
    console.error(err);
    _db.close();
  });

  result.then(() => _db.close());

  return result;
}

// основная работа приложения будет тут
co(function*() {
  var users = yield getUser(db, 'user-1', 'users');
  console.log('users: ', users);
}).catch(err => {
  console.error('Произошла страшная ошибка!', err);
});

But I would also make some function on your meta that will open a connection to the database and not close it. For each time to open/close connection with a DB - very expensive operation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question