我正在try 为应用程序开发数据聚合功能.用户应该能够输入一个名称,然后在数据库集合中搜索该名称并返回集合.

控制器:

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

路由:

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

对于'author': author,我试图使用author作为变量名,但我不知道如何构造控制器和路由,以便接收参数,以便在postman上检索值.

推荐答案

我想你在《postman 》中的请求应该是这样的:

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

当API收到您的请求时,控制器中的req对象中就有了主体,因此,如果您想在聚合中使用author字段,只需访问:req.body.author即可.

您的控制器可能具有下一个 struct :

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) => {...},
}

路由正常:

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

我希望我能帮上忙

Node.js相关问答推荐

如何呈现ejs.renderFile中包含的子模板?

请求正文未定义

为什么这个verifyToken函数从未被调用过?

Express Web 服务器部署到 prod 但 GET 返回超时错误

当API返回400状态代码时,使用Reactjs fetch获取错误消息

如何在Node.js的telegraf.js命令中添加参数?

具有项目外部子路径导入的 Firebase 函数

为什么这个 module.export 函数如果我直接传递它就不起作用,但如果我将它包装在一个匿名函数中就可以工作

在对象数组中的数组中嵌套 $lookup - Mongodb

如何使用 NodeJS 加密模块将 ECDH 密钥转换为 PEM 格式

Zod 模式中的self 数组

在 Atlas 触发器(Node JS)中正确初始化 Firebase 管理 SDK

表达限制资源属于特定用户的优雅方式

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

通过 npm 导入 Sass

node.js 中 res.setHeader 和 res.header 的区别

ChildProcess 关闭、退出事件之间的区别

使用 pg-promise 进行多行插入

yarn 和 npm 的主要区别是什么?

promise 回调返回promise