Home > Blockchain >  use a variable value in lookup mongoose expression
use a variable value in lookup mongoose expression

Time:12-24

I am using a mongoose model that brings documents and I add an aggregate to "join" with other collection. The real problem is when I use aggregate I cannot filter documents in the "original" collection (similar to findOne()). So when I use the aggregate function I get all documents but I just need 1.

i.e. (this is only an example for a point describe)


Collection A = {id,name,birthdate,dni} 
   Collection B = {avatar,dni.....} 
   a.aggregate([ '$lookup': {
       'from': 'avatars',
       'localField': 'dni',
       'foreignField': 'dni',
       'as': 'aditionalinfo' 
   } ])

this result in a full collection A additionalinfo object from B for each document but supposed to bring one person from collection A with the additional data (additionalinfo). I mean, I need to bring one document "joined" with the corresponding document from the other collection.

here is the last code I tried

let ley = await leyes.aggregate([
{         
 '$lookup': {           
   'from': 'digessituacion',           
   'localField': 'idsituacio',           
   'foreignField': 'idsituacio',            
   'as': 'situacion'        
 }       
}, {
   '$lookup': { 
      'from': 'digescategoria',            
      'localField': 'catego',            
      'foreignField': 'catego',            
      'as': 'categoria'         
    }
   }, 
{         
  '$match': { 
     'ley': 8996 // this is the number which I need to set variable cause is passed from params         
  }
}]);

this is the schema

    import { Schema, model } from "mongoose";
    const leyesSchema = new Schema(
      {
        ley: Number,
        resumen: String,
        notas: String,
        txtley: String,
        catego: String,
        detcatego: String,
        idsituacio: Number,
        promulgada: Date,
        sancionada: Date,
       
      },
      { timestamps: false, versionKey: false }
    );
    export default model("leyes", leyesSchema);

and the Schema of collection needed to "join"

    import { Schema, model } from "mongoose";
    const digessituacionSchema = new Schema(
      {
        idsituacio: Number,
        situacion: String,
      },
      { timestamps: false, versionKey: false }
    );
    export default model("digessituacion", digessituacionSchema);

if I put the number manually works but is not usable cause it must be a variable. Anyone knows the way for do this? It is possible?

CodePudding user response:

When the req.params is parsed, they are always parsed as type string. Since your ley field is of type number, you have to parse it first:

"$match": { 
  "ley": parseInt(req.params.ley, 10)     
}
  • Related