1

how to use search_key variable as field value instead of static value BRO

if(search_key!=''){

  dbo.collection("assets").aggregate([
    { 
      "$match": {  $and: [ { status: 1 }, { $or: [ { maker_name : /^.*BRO.*$/i }, { serial_number : /^.*BRO.*$/i  } ] } ] }
    },  
    {
      $lookup:
       {
         from: 'asset_type',
         localField: 'asset_type',
         foreignField: 'asset_type_id',
         as: 'asset_type_details'
       }
     }
    ]).sort({_id:-1}).toArray(function(err, result) {
    if (err) throw err;
    res.status(200).json({'return_data': result });
    db.close();
  });

}
Saurabh Mistry
  • 8,903
  • 4
  • 33
  • 51

3 Answers3

0

We need to pass a string to the function. so we can simply change that by passing query string.

        if(search_key!=''){
            let query_string = "/^.*" + search_key + ".*$/i" // we are creating the query string here
            dbo.collection("assets").aggregate([
                { 
                    "$match": {  $and: [ { status: 1 }, { $or: [ { maker_name : query_string }, { serial_number : query_string } ] } ] }
                },  
                {
                    $lookup:
                     {
                       from: 'asset_type',
                       localField: 'asset_type',
                       foreignField: 'asset_type_id',
                       as: 'asset_type_details'
                     }
                 }
                ]).sort({_id:-1}).toArray(function(err, result) {
                if (err) throw err;
                res.status(200).json({'return_data': result });
                db.close();
            });

        }
0

try like this :

if(search_key!=''){

  dbo.collection("assets").aggregate([
    { 
      "$match": {  $and: [ { status: 1 },
                           { $or: [ 
                            { maker_name : '/^.*'+ search_key +'*$/i' },
                            { serial_number : '/^.*'+ search_key +'*$/i'  } 
                            ]
                           }  
                         ]
                }
    },  
    {
      $lookup:
       {
         from: 'asset_type',
         localField: 'asset_type',
         foreignField: 'asset_type_id',
         as: 'asset_type_details'
       }
     }
    ]).sort({_id:-1}).toArray(function(err, result) {
    if (err) throw err;
    res.status(200).json({'return_data': result });
    db.close();
  });

}
Saurabh Mistry
  • 8,903
  • 4
  • 33
  • 51
0

Try this way

{ serial_number: { $regex: `${search_key}.*`, $options: 'i' } }

Use this same thing for maker_name also.

This is works for me.

Sachin Shah
  • 3,826
  • 2
  • 12
  • 36