简体   繁体   中英

Return array with single string value in MongoDB with Meteor

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?

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; });
};

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()...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM