Home > database >  I'm trying to pass a var from a html form into an mongodb aggregate function
I'm trying to pass a var from a html form into an mongodb aggregate function

Time:10-23

So im using a mongoose.connection.db.collection(Collcation_name).aggregate the problem is that im trying to pass a var from a html form when i try to use the var it' doesn't recognize the value of it.

    app.post("/filter", function(req, res){
      query.query(
        dsName,
        req.body.q1,
        req.body.q2,
        req.body.q3
      );
    });

    async function query(dataSetName,q1,q2,q3){
      //q1, q2, q3 are key values that exists in the schema
      var filterd = await mongoose.connection.db.collection(dataSetName).aggregate([
                                                                          // trying to pass q1 and q2 here the value of q1 and q2 is the column names in the database
                                                                          {$project:{ _id:0, q1:1, q2:1}}])
                                                                          .toArray()
      console.log(filterd);
    }

This is the output from the console.log(filtered function)

[ {}, {}, {}, {}, {}, {} ]

CodePudding user response:

When you do it like that, MongoDB will assume that the names of fields are q1 and q2.

You can instead create a projection object before passing it to the query, where keys would be the actual names of the q1 and q2:

const projection = { _id: 0 };
projection[q1] = 1;
projection[q2] = 1;

await mongoose.connection.db.collection(dataSetName).aggregate([
  {
    $project: projection
  }
])                                                                
  • Related