Mongodb return array of strings instead array of objects Mongodb return array of strings instead array of objects mongodb mongodb

Mongodb return array of strings instead array of objects


There is a way to select only tokens that require less processing using the mongodb aggregation framework

UserMdl.aggregate(  { $match: { token : { $exists : true }}},  { $project: { _id: 0, token: 1 }},  function onUsersFound(err, tokens) {    console.log(tokens);  }););

This constructs an aggregation pipeline that first matches all documents that have a token field and then selects the token field and suppresses _id selection by using _id : 0 in the $project pipeline step.

The post processing step would look like this:

function postProcess(tokenObjects) {  if (!tokenObjects) {    return [];  }  return tokenObjects.map(function(tokenObject) { return tokenObject.token; });  }

See also the mongoose docs for more detail on the aggregation function.


You don't need to do anything special. Just change one thing in your code:

Your code

UserMdl.find().exists('token').select('token').exec(function onUsersFound(err, userMdls) {    console.log(userMdls);    // (*) Change this to...});

Change

UserMdl.find().exec((err, users) => {    console.log(users.map(user => user.token));    // ...(*) to this});

No need to use select & exists functions


EDIT

The best option is Mongoose distinct function:

const tokens = await UserMdl.distinct('token');

If you want condition then:

const tokens = await UserMdl.find(/* condition */).distinct('token');

Thats it