Do find using the result of another find (which returns multiple objects)

1

What I want to do is with the result of a find (which returns several objects to me), again doing a find in DB looking for all the records that have the id of the records that I got in the previous find (taking into account note that they are multiple objects and with different id).

in the following code will help me with the comments to explain it better:

function get(req,res){
    TG.find({_teacher:req.user.sub},(err,groups)=>{
        if(err){
            res.status(500).send({message:'Hubo un error al crear el grupo'});
        }else{
                if(groups){
                    **// aqui intento hacer un find con el id de los objetos
                      provenientes del anterior find, quiero saber como
                      hacerlo porque en este momento groups._id me devuelve
                      undefined ya que son varios objetos y no solo uno**
                    Groups.find({_id:groups._id},(err,groups)=>{
                        if(err){
                            res.status(500).send({message:'Error al buscar los grupos'});
                        }else{
                            if(groups){
                                res.status(200).send({groups});
                            }else{
                                res.status(404).send({message:'No tienes grupos'});
                            }
                        }
                    });
                }else{
                    res.status(404).send({message:'No tienes grupos'});
                }
             }
    });
}

Thank you very much

    
asked by Freak24 08.03.2018 в 03:58
source

1 answer

1

First : the first query returns a cursor groups . The nested query does the same. That is called doing shadowing and it is a bad practice. If your first collection is teachers use that name for the cursor.

Second , instead of using cursors, you can use Collection.find (). toArray () to get the results as an array and not have to go asking for next of the cursor. p>

Finally : The most up-to-date MongoDB drivers for nodejs return a promise if you do not pass a callback to Collection.find so you could do:

TG.find({_teacher:req.user.sub}).toArray().then(teachers)=>{

    if(!teachers.length) {
        res.status(404).send({message:'No tienes grupos'});
        return;
    }
    var groups_array = [],
    groups_promises = teachers.map(function(teacher) {
        return Groups.find({_id: teacher._id}).toArray().then((groups) => {
            groups_array.push(groups);
            return;
        });
    });

    return Promise.all(groups_promises).then(()=>{
        res.status(200).send(groups_array);
        return;
    });


}).catch((err)=> {
        res.status(500).send({message:err.message});
});

This returns an array of arrays. If you want a single array with all the groups, you can use

groups_array = groups_array.concat(groups);
    
answered by 08.03.2018 / 11:48
source