How to retrive all userIds as a list from a collection in Mongodb + Express.js?
我正在使用https://github.com/mongodb/node-mongodb-native?_ga=1.224176859.1706529023.1457418359
用于我的node.js项目。我需要从Mongo集合(用户)中获取所有用户ID(作为列表)。是否可以从给定的Mongo驱动程序本身执行此操作?
这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); }); }); |
用户集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | { "_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" :"" } |
一种更优雅的方法是在集合上简单使用mongo的
下面显示了如何将其应用于您的案例:
1 2 3 4 5 6 7 8 9 10 11 | 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); }); |
尝试使用
1 2 3 4 5 6 7 8 9 10 11 | 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); }); |
在项目上运行