Prateekro
Prateekro

Reputation: 566

Get value of "name" in node js

Category = collection.find({},{ name: true }).toArray();
console.log("Categories Found", Category);

Output:

Promise { [ 
            { name: 'Agriculture' },
            { name: 'engineer' } 
        ] }

How do I get the value of name? (NOTE: Working in node JS)

Upvotes: 2

Views: 1723

Answers (3)

chridam
chridam

Reputation: 103375

To get the values in an array you can use the distinct() method as follows:

collection.distinct("name").then(function(categories) { 
    console.log("Categories Found", categories); 
    console.log("First Category", categories[0]); 
})

or using a callback function as:

collection.distinct("name", function(err, categories) { 
    if (err) throw err;
    console.log("Categories Found", categories); 
    console.log("First Category", categories[0]); 
})

Upvotes: 0

David Gatti
David Gatti

Reputation: 3701

Since you get back a promise, you can use .then() to get to the result, and then get to your data with a loop :)

collection
    .find({}, { name: true })
    .toArray()
    .then(function(result) { 

        result.forEach(function(data) {

            console.log("name: %s", data.name); 

        });

    });

Have fun :)

Upvotes: 3

GilZ
GilZ

Reputation: 6477

toArray is an asynchronous function that returns a promise. You can get your categories in one of two ways:

Promise style:

collection.find({},{ name: true }).toArray()
    .then(categories => {
        console.log(categories);
    });

Callback style:

collection.find({},{ name: true }).toArray((err, categories) => {
    console.log(categories);
});

Of course, it is a good practice to have some error handling: add .catch to the promise chain, or check if err is truthy in the callback.

Upvotes: 3

Related Questions