dilusha_dasanayaka
dilusha_dasanayaka

Reputation: 1441

How to get result to array in mongoose?

I’m new to angular and I just started dealing with mongodb using mongoose.

In my application I need to get name list of drivers as string array, but, I’m getting array of objects with object id.

{
            "_id": "5aa90ab23c49a72488afab7a",
            "name": "mr. Rusiru ekanayaka"
        },
        {
            "_id": "5aa90d4ba8c6b35438a8b132",
            "name": "mr. Gihan ekanayaka"
        },
        {
            "_id": "5aa90d56a8c6b35438a8b133",
            "name": "mr. Gihan ekanayaka"
        }
}

But I need something like this,

[
  ' mr. Gihan ekanayaka,
  ' mr. rusiru ekanayaka ',
  ' mr. Gihan ekanayaka '
]

I think I can re-format this in my backend by looping through the object. By is there anyway to get only one field of document in collection as string array without object id?

In my Driver model I do like this.

module.exports.getDrivers = function(callback){
  Driver.find({},'name',callback);
}

Upvotes: 0

Views: 2476

Answers (3)

Vince Bowdren
Vince Bowdren

Reputation: 9208

One way to do it is to use a map, for example like this:

Driver.find({}).map(driver => driver.name);

That (with adjustments to the code to fit your coding environment) will return an array of driver.name items, like this:

[
  "mr. Rusiru ekanayaka",
  "mr. Gihan ekanayaka",
  "mr. Gihan ekanayaka"
]

Upvotes: 0

Houssem Romdhani
Houssem Romdhani

Reputation: 332

Try this:

module.exports.getDrivers = function(callback){

Driver.distinct('name', callback);

}

Upvotes: 1

charan tej
charan tej

Reputation: 1054

Try this

module.exports.getDrivers = function(callback){
  Driver.find({},{'_id' : 0,'name' : 1},callback);
}

Upvotes: 2

Related Questions