从一组id到一组名称(mongo,nodejs)

问题描述 投票:2回答:2

我一直在探索这几个小时...感谢您的帮助。

我有一个“用户”集合,每个用户都有一个_id和一些名字(UsernameFirstNameLastName)。我还有一个“组”集合,每个组都有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 + ")";
        });
    }

但是因为mongo是异步的,所以没有用。经过一些阅读,我安装了async,我认为这将解决我的问题。我尝试了async,async.whilstasync.times,甚至试图用async.waterfall破解一些东西 - 但没有任何效果 - 几乎都以相同的方式结束:数组在字符串被推送之前传递。

也许我对这项任务的态度是错误的?

javascript node.js mongodb asynchronous async.js
2个回答
4
投票

如果你已经拥有一个用户id数组,那么最好使用map()方法将该字符串数组转换为ObjectIds数组,然后在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();
         });  
});

另一种方法是采用聚合路径,您可以使用$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();
    });  
});

3
投票

您可以使用$in operator通过单个查询查找多个用户。这对性能更好,对异步性更少麻烦。

// Convert the list of ids to mongo object ids
var objectIds = arrOfIds.map(function(item) {
  return ObjectId(item);
});

// Use the $in operator to find multiple users by id
users.find({ "_id": { $in: objectIds } }, function(err, result) {
  // result is now a list of users
});
© www.soinside.com 2019 - 2024. All rights reserved.