简体   繁体   中英

query mongo based on results of query

I have this mongoose query:

let rE = await cR.find({myid: "xxxxxx"});

now this query will return multiple results, in which I then need to query another model based off of the rE.class_id , which is returned through rE , the query above. So I do this:

let cla = await Cl.find({_id: rE.class_id});

however, that obviously doesn't work because rE.class_id gets returned as multiple objects, so placing rE.class_id just wont work. How can I get this to work?

If you are trying to get all Cl models where _id = (classIds of models rE) Then you can try this one:

let rE = await cR.find({myid: "xxxxxx"});
const classIds = rE.map(r => r.classId);
let cla = await Cl.find({_id: {$in: classIds}});
const data = await cR.aggregagte([
  {
    '$match': {
       myid: "xxxxxx" 
    }
  },
  {
    '$lookup': {
      'from': 'rE', 
      'localField': 'authorId', 
      'foreignField': '_id', 
      'as': 'cla'
    }
  }
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM