Neekoy
Neekoy

Reputation: 2533

NodeJS get only value of MongoDB result

I'm trying to get only the value of a specific MongoDB field, and have the following code:

var collection = db.collection('people');

collection.find({"name" : "John" }, { phone : 1, _id : 0 }).toArray(function (err, result) {
    if (err) {
        console.log(err);
    } else if (result.length) {
        console.log(result);
    } else {
        socket.emit("No documents found");
    };
});

This works great however it gives me the following result:

[ { phone: 112233 } ]

How can I edit the query so that it will return only "112233", or how can I split the array "phone: 112233" so that it will give me the value only?

Any help is greatly appreciated.

P.S. I tried forEach and MongoDB aggregate, to no avail as of the moment.

Upvotes: 1

Views: 2168

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

Split it like this:

result[0].phone

Upvotes: 3

Related Questions