Home > front end >  How can I make an request params to mongo db from node js and swagger?
How can I make an request params to mongo db from node js and swagger?

Time:06-01

What I have tried is to get all the data by createdBy param. createdBy has a user phone number value.

controller

exports.getLocation = asyncHandler(async (req, res, next) => {

    const createdBy = req.params.createdBy
    console.log('created', createdBy) // its empty 

    const getLocation = await Location.find( {createdBy: createdBy} )

    res.status(200).json({
        success: true,
        msg: "Getting all the locations of the user",
        data: getLocation
    })
}) 

routes

 /**
 * @swagger
 * /location/getLocation/:createdBy:
 *   get:
 *     summary: getting the location of the user by phone number
 *     tags: [Location]
 *     requestBody:
 *       required: false
 *       content:
 *        application/json:
 *          schema:
 *            $ref: '#/components/schemas/Location'
 *
 *     responses:
 *       200:
 *         description: the location has been recivied
 *       500:
 *         description: Some server error
 */
  router.get("/getLocation/:createdBy", getLocation) 

The idea is to put the param in a request body, to get all the data of the createdBy key in the database. The get method doesn't accept a request body. How can I put a param so I can get the data from the database?

To let you know, I'm using the swagger request body to execute the API, and this API is for a react-native application.

CodePudding user response:

You have to correct your swagger annotation for createdBy property,

  • use {createdBy} instead of :createdBy in URL
  • use parameters property of swagger and in that declare the createdBy property with path type
  • requestBody is not required because you are using GET request type
/**
 * @swagger
 * /location/getLocation/{createdBy}:
 *   get:
 *     summary: getting the location of the user by phone number
 *     tags: [Location]
 *     parameters:
 *       - name: createdBy
 *         description: Created By
 *         in: path
 *         required: true
 *     responses:
 *       200:
 *         description: the location has been recivied
 *       500:
 *         description: Some server error
 */

router.get("/getLocation/:createdBy", getLocation);
  • Related