Home > Mobile >  Input field function when aggregating data in node and mongoDB
Input field function when aggregating data in node and mongoDB

Time:03-14

I am trying to develop a data aggregation feature for an application. The user should be able to enter a name and it'll search the database collection for that name and return the collection. I am trying to implement it using node.js but i am confused as to how to pass a parameter for the name.

Controller:

exports.DAFacility_author_search = (req, res) => {
  DAFacility.aggregate([
    [
      {
        '$match': {
          'author': author
        }
      }
    ]
  ]).then((DAFacility) => {
    res.send(DAFacility);
  })
  .catch((e) => {
    res.send(e);
  });
};

Route:

router.get('/DAFacilityAuthor', DAFacilityController.DAFacility_author_search)

For the 'author': author i am trying to use author as the variable name but i dont exactly know how to structure the controller and router to take in a parameter so that i can retrieve a value on postman. Any help would be great Thank you

CodePudding user response:

I suppose that your request in postman will be something like:

{
    "author": "foo",
    ...
}

When your request is received by the API, the body is available in your req object in the controller, so, if you want to use author field in your aggregate, you simply access: req.body.author.

Your controller could have the next structure:

export const DAFacilityController = {
    DAFacility_author_search: (req, res) => {
        DAFacility.aggregate([
            {'$match': {'author': req.body.author}}
        ])
    .then((DAFacility) => {
        res.send(DAFacility);
    }).catch((e) => {
        res.send(e);
    });
    },

    DAFacility_another_method: (req, res) => {...},
}

The router is ok:

router.get('/DAFacilityAuthor', DAFacilityController.DAFacility_author_search);
router.get('/DAFacilityAuthor/<something>', DAFacilityController.DAFacility_another_method);

I hope I helped

  • Related