Reputation: 1334
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?
Upvotes: 0
Views: 366
Reputation: 103345
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; });
};
Upvotes: 1
Reputation: 5088
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()...
Upvotes: 0