Yog*_*evy 2 javascript asynchronous mongodb node.js async.js
我已经为此花了几个小时...谢谢您的帮助。
我有一个“用户”集合,每个用户都有一个_id和一些名字(Username,FirstName,LastName)。我也有一个“组”集合,每个组都有一个Members,它是用户数组_id。
刚开始,我想要一个简单的函数,该函数接收一个id数组并将其转换为一个格式很好的字符串数组:FirstName + " " + LastName + " (" + Username + ")"。因此,我为此做了一个简单for的说明:
var ans = [];
for (i=0; i<arrOfIds.length; i++) {
users.find({"_id": ObjectID(arrOfIds[i])}, function(err, result){
ans.push = result.FirstName + result.LastName + "(" + result.Username + ")";
});
}
Run Code Online (Sandbox Code Playgroud)
但是由于mongo是异步的,所以没有用。经过一番阅读后,我安装了async,我认为它将解决我的问题。我只是尝试了async,async.whilst,async.times,甚至尝试用async.waterfall破解某些东西-但没有任何效果-几乎都以相同的方式结束了:在将字符串压入字符串之前传递了数组。
也许我对这个任务的态度是错误的?
如果您已经有一个用户ID数组,那么最好是使用map()方法将字符串数组转换为ObjectId数组,然后在find()查询中使用$in运算符,该运算符选择文档,其中字段的值等于指定的数组。
您将需要toArray()在find()游标上调用方法,以便可以在数组中获取结果,进一步操作该数组以返回所需的结果,如下所示:
var MongoClient = require('mongodb').MongoClient,
ObjectID = require('mongodb').ObjectID;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
// Get users collection
var Users = db.collection('users');
// Retrieve all the documents in the collection
Users.find({ "_id": { "$in": arrOfIds.map(ObjectID) } })
.toArray().then(function(users) {
// Create array of names
var ans = users.map(function (u){
return u.FirstName + " " + u.LastName + " (" + u.Username + ")";
});
// Do something with the result
console.log(ans);
db.close();
});
});
Run Code Online (Sandbox Code Playgroud)
另一种方法是采用聚合路线,您可以在其中使用$group管道步骤通过$push和$concat运算符创建所需的数组。
考虑运行以下聚合操作:
var MongoClient = require('mongodb').MongoClient,
ObjectID = require('mongodb').ObjectID;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
// Get users collection
var Users = db.collection('users');
// Retrieve all the documents in the collection
Users.aggregate([
{ "$match": { "_id": { "$in": arrOfIds.map(ObjectID) } } },
{ "$group": {
"_id": null,
"users": {
"$push": {
"$concat": ["$FirstName", " ", "$LastName", " (", "$Username", ")"]
}
}
} }
]).toArray().then(results => {
const ans = results[0].users;
// Do something with the result
console.log(ans);
db.close();
});
});
Run Code Online (Sandbox Code Playgroud)