如何从Mongodb + Express.js的集合中检索所有的用户标识?

我为我的node.js项目使用https://github.com/mongodb/node-mongodb-native?_ga=1.224176859.1706529023.1457418359 。 我需要从Mongo集合(用户)获取所有用户ID(作为列表)。 是否有可能从给定的蒙戈司机本身?

这是我的代码:

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

用户集合

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

一个更优雅的方法是简单地在集合上使用mongo的distinct方法。 这将为单个集合中的指定字段查找不同的值,并将结果返回到数组中。

以下显示如何将其应用于您的案例:

 var collection = db.collection('user'); // Peform a distinct query against the userId field collection.distinct('userId', function(err, result) { if (err) { throw err; return res.status(400).send(err); } console.log(result); return res.status(200).send(result); }); 

尝试使用_.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); }); 

在运行npm install --save lodash在你的项目上npm install --save lodash