E
E
eXe1en72016-05-31 00:18:29
MongoDB
eXe1en7, 2016-05-31 00:18:29

How to return value from collection.find()?

var shortLinks = [];

    Link.find({}).exec(function (err, links) {

        if (err) {
            console.log(err);

        } else {

            links.map(link => {
                shortLinks.push(link.shortLink);
            });
        }
    });
    console.log(shortLinks); // тут массив пустой

When calling an array within find(), it is filled and everything is ok, but how to return it so that it becomes available outside of find

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kumanin, 2016-05-31
@eXe1en7

exec() will return a Promise and process it.

var shortLinks = Link.find().exec();
// ...

shortLinks.then(function(links){
  // work with links
}, function(err){
  // some error
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question