Neekoy Neekoy - 5 months ago 29
Node.js Question

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.

Answer

Split it like this:

result[0].phone