Mongodb返回string数组而不是数组对象

我使用这段代码来查询用户在mongo db中的令牌(nodejs with mongoose):

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

所以我得到:

 [ { _id: 5447e36a60e5d15678de486c, token: '34f83483cc0ed82e17c162d' }, ... ] 

有什么办法可以得到一个string数组:

 [ '34f83483cc0ed82e17c162d', ... ] 

现在我正在做的是后处理响应。 我问这个问题,因为我认为也许有一个更快的方法来做mongoose/ mongodb查询。

编辑

后期处理我现在正在做:

 var results = []; userMdls.forEach(function (userMdl) { results.push(userMdl.token); }); 

编辑

感谢saintedlama的回应,我做了一些testing,结果如下:

数据:14.976文件
testing:100
结果:

.find().exists('token').exec(..) :1236.33 ms
.aggregate({..}) :136.07 ms

testing代码:

  var start, end, time, firstTimes = [], secondTimes = [], test = 0, firstFinal, secondFinal, i, Q = require('q'), UserMdl = require('models/user'), u, tokens = []; function promiseWhile(condition, body) { var done = Q.defer(); function repeatTest() { start = new Date().getTime(); UserMdl.find().exists('token').exec(function onUserMdlFound(err, users) { for (u = 0; u < users.length; u += 1) { tokens.push(users[u].token); } end = new Date().getTime(); time = end - start; firstTimes.push(time); start = new Date().getTime(); tokens = []; UserMdl.aggregate({ $match: { token: { $exists: true } } }, { $project: { _id: 0, token: 1 } }, function onUserMdlFoundAggregate(err, users) { for (u = 0; u < users.length; u += 1) { tokens.push(users[u].token); } end = new Date().getTime(); time = end - start; secondTimes.push(time); tokens = []; if (condition()) { Q.when(body(), repeatTest, done.reject); } else { return done.resolve(); } }); }); } Q.nextTick(repeatTest); return done.promise; } function printResult() { firstFinal = 0; secondFinal = 0; for (i = 0; i < firstTimes.length; i += 1) { firstFinal += firstTimes[i]; secondFinal += secondTimes[i]; } console.log("First mean: " + firstFinal / i + " - Second mean: " + secondFinal / i); } test = 1; promiseWhile(function condition() { return test <= 300; }, function body() { console.log("running test: " + test); test++; return Q.delay(0); // arbitrary async }).then(function () { console.log("Finish testing"); printResult(); }).done(); 

有一种方法可以仅使用mongodb 聚合框架select需要较less处理的令牌

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

这构造了一个聚合pipe道,首先匹配具有标记字段的所有文档,然后select标记字段,并通过在$project pipeline步骤中使用_id : 0来取消_idselect。

后处理步骤如下所示:

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

有关聚合函数的更多详细信息,另请参阅mongoose文档 。