0

Hi I am trying to convert a mongodb collection to array and its not working giving me blank array any help would be appreciated playingCollection is mongodb collection.

var state = [];

playingCollection.find({},function(err, companies) {
    companies.each(function(err,company){
            if (company !== null) {
                var obj = company.playername;
                state.push(obj);
            }
        }
    );
});

console.log(state); 

2 Answers 2

1

It's an asynchronous call.

If you log it inside the callback, it shouldn't be empty:

playingCollection.find({},function(err, companies) {
    companies.each(function(err,company){
            if (company !== null) {
                var obj = company.playername;
                state.push(obj);
            }
        }
    );
    console.log(state); 
});    
Sign up to request clarification or add additional context in comments.

Comments

0

Use toArray

playingCollection.find({}).toArray(function(err, companies)

1 Comment

still blank, however just a fyi if do console.log(obj) instead of state.push(obj); it works fine and prints all the elements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.