Amila Iddamalgoda Amila Iddamalgoda - 4 months ago 11
Node.js Question

How to retrive all userIds as a list from a collection in (Mongodb + Express.js)

I'm using https://github.com/mongodb/node-mongodb-native?_ga=1.224176859.1706529023.1457418359
for my node.js project. And I need to get all the user ids (as a list) from the mongo collection (user). Is it possible to do it from the given mongo driver itself. Please help me out. Here's my code.

MongoClient.connect(mongoUrl, function(err, db) {
if (err) {
throw err;
return res.status(400).send(err);
}

db.collection('user').find({},{'password': false}).toArray(function(err, result) {
if (err) {
throw err;
return res.status(400).send(err);
}
console.log(result);
return res.status(200).send(result);
});
});


user collection

{
"_id" : ObjectId("5789c80733118ab81b661160"),
"username" : "",
"firstName" : "Test",
"lastName" : "",
"userId" : 404040,
"address" : "test address",
"phoneNumber" : 1120202000,
"isActive" : true,
"subscriptionIdList" : [
2220,
22252,
6526,
70505
],
"password" : "",
"createdAt" : "2016­06­21T11:22:11.089Z",
"updatedAt" : "2016­07­21T11:22:11.089Z",
"lastSubscribedAt" : ""
}

Answer

Try using _.map():

var _ = require('lodash');

db.collection('user').find({}, {_id: 0, userId: 1}).toArray(function (err, result) {
  if (err) {
    throw err;
    return res.status(400).send(err);
  }
  var userIds = _.map(result, 'userId');
  console.log(userIds);
  return res.status(200).send(userIds);
});

After running npm install --save lodash on your project.