如何从节点 js 和 swagger 向 mongo db 发出请求参数?

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

我尝试的是通过 createdBy 参数获取所有数据。 createdBy 有一个用户 phone 数值。

控制器

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
    })
}) 

路线

 /**
 * @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) 

思路是将param放在request body中,获取数据库中createdBy键的所有数据。 get 方法不接受请求正文。 我如何放置参数以便从数据库中获取数据?

让你知道,我正在使用 swagger 请求正文来执行 API,而这个 API 是用于 react-native 应用程序。

您必须更正 createdBy 属性,

的 swagger 注释
  • 在URL
  • 中使用{createdBy}代替:createdBy
  • 使用 parameters 属性 of swagger 并在其中声明 createdBy 属性 和 path 类型
  • requestBody 不是必需的,因为您使用的是 GET 请求类型
/**
 * @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);