Dmitry Mogilevich Dmitry Mogilevich - 6 months ago 11
Node.js Question

How to return value in collection.find({})

var shortLinks = [];

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

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

} else {

links.map(link => {
shortLinks.push(link.shortLink);
});

}
console.log(shortLinks);//shortLinks has values, all okey
});

console.log(shortLinks); //shortLinks is empty


i need to use shortLinks after Link.find({}) but array is empty.
Need to return shortLinks.

Answer

Callbacks. The function(err, links) is called asynchronously, so shortLinks isn't populated until that function is called. Your bottom console.log is being called first, due to how callbacks work.

https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks