0

I have a function in JS that returns a value from a Mongo query. What I would like it to return would be an array with a single string value of the Address field. This is what I've got:

mapAddress = function() {
  return Demographic.find( {Fname: 'JOHN'}, {Lname: "DOE"}, {Address: 1, _id: 0} ).fetch()[0];
};

A query for John Doe is made and searches for those first and last names. Return only the Address field value in an array. I'm not sure if fetch() returns an array or not. How is this done?

2 Answers 2

1

To get the desired result, use the map() method on the find() cursor which returns an array. I suppose you want a result like, for example:

var mapAddressArray = ["123 ABC Apartments"];

You can even get this without using the field specifiers:

mapAddress = function() {
    return Demographic.find({ 
        "Fname": "JOHN", "Lname": "DOE" 
    }).map(function (a){ return a.Address; });
};
Sign up to request clarification or add additional context in comments.

3 Comments

This returns an empty array. I'm using first and last names I know are in the collection with address field values.
Can you edit your question to include some sample documents in the collection and what your expected output is for some given first and last names?
Many thanks for your help. Yes, your method does work from the console. I was trying to print to the console from Meteor using a simple function and function call. I didn't realize that if the console.log is inside a regular named javascript function, and the function is called, it prints an empty array. The only way it worked is if I put the console.log inside an event map or helper. I wasn't aware of this.
0

fetch() does return an array, possibly empty if no documents matched.

This seems to be what you want:

mapAddress = function() {
  return Demographic.find( {Fname: 'JOHN', Lname: "DOE", Address: 1, _id: 0} ).fetch()[0].Address;
};

Although if no document matched, this code would throw an error. You probably want to do a check for that.

Also, you don't need to search by all fields, if you have the id, that's enough. So this is a better query to use:

Demographic.find({_id: 0}).fetch()...

2 Comments

Trying to make that work. Doing a query for a first and last name I know is in the collection, comes up with an error, 'undefined is not an object' when trying to print to the console.
Probably because it didn't match anything. You need to check for things being null. Make sure the document actually exists

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.