0

I am using MongoDB with Node.js. I want to make a function that I can call with the arguments of some base values (to identify the document) and then the name of the field I want the function to return the value of.

My documents look like this:

{
 "name": "John Smith",
 "email": "[email protected]",
 "phone": "555-0125"
}

I want to call the function like this:

var phone_number = GetInfo({"name":"John Smith"}, "phone");
console.log(phone_number); // This should output "555-0125"

How do I go about this using the Node.js driver for MongoDB. The documentation suggests I will need to take a callback-oriented or Promise-oriented approach but I have no idea what either of those things mean.

asked Sep 19, 2016 at 20:56

2 Answers 2

1

This is the promise syntax that is mentioned in the documentation:

// Retrieve all the documents in the collection
collection.find().toArray(function(err, documents) {
 test.equal(1, documents.length);
 test.deepEqual([1, 2, 3], documents[0].b);
 db.close();
});

notice when find() is called, it returns a Cursor Object which allows you to filter/select/read the results of the query. Since find() is an asynchronous (deferred execution) call javascript has to attach a callback that will be executed when the result of find() is resolved.

MDN also has more information about Promise objects here for further reading: Promises

In the case of your code, you could do this:

// collection defined above this code snippet.
collection
 .findOne({"name":"John Smith"})
 .forEach(function(doc) { console.log(doc.phone) });
answered Sep 19, 2016 at 21:08
Sign up to request clarification or add additional context in comments.

Comments

0

You can use co generator for this. It is easy to understand how it work.

//your function call
var phone_number = GetInfo({"name":"John Smith"}, {"phone":1});
//your function description
function GetInfo(query, projection) {
 //using generator
 co(function*() {
 //connect to db
 let db = yield MongoClient.connect(url);
 let collectionName = db.collection(colName);
 collectionName.find(query, projection).toArray((err, doc)=> {
 if (err) console.log(err);
 //your data
 console.log(doc);
 return doc;
 }
db.close();
}

You can also use native callbacks for this if you want

answered Sep 19, 2016 at 21:28

1 Comment

Hi - I tried this. the document prints fine but the value of phone_number is still undefined.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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