【问题标题】:How to filter Data using email in MongoDB?如何在 MongoDB 中使用电子邮件过滤数据?
【发布时间】:2022-08-20 13:33:26
【问题描述】:

如何通过电子邮件从 MongoDB 获取数据?这是一个例子:

       _id: Objectid(\'6274e58826914a298567e5f8\'),
        \"name\": \"Vauxhall Mokka\",
        \"supplier\": \"Vauxhall\",
        \"email\": \"abc@def.com\",
        \"price\": 30000,
        \"quantity\": 30,
        \"img\": \"https://i.ibb.co/SQqBNXy/getImage.png\",
        \"sold\": 0

我可以使用以下代码通过 _id 轻松获取项目:

 app.get(\'/cars/:id\', async (req, res) => {
            const id = req.params.id;
            const query = { _id: ObjectId(id) };
            const result = await serviceCollection.findOne(query);
            res.send(result);
        });

但是为什么我不能对电子邮件做同样的事情呢?当我申请\'/cars/:email\' 时,服务器出现故障。如果我得到带有 id 的项目,那为什么不能通过电子邮件得到呢?

  • 你如何将电子邮件写入URL?喜欢/cars/user@example.com?尝试对 at 符号进行 URL 编码:/cars/user%40example.com。然而,将电子邮件写入 URL 路径是非常不寻常的。而是将其放在查询字符串 (/cars/filter?email=user%40example.com) 中并从 req.query.email 中读取。您应该正确转义特殊字符(at-sign 在 URL 中具有特殊含义),所以

标签: mongodb


【解决方案1】:

没有理由为什么这不应该工作

 app.get('/cars/:email', async (req, res) => {
   const query = { email: req.params.email };
   const result = await serviceCollection.findOne(query);
   res.send(result);
 });

当“服务器宕机”时,它会给你一个错误信息吗?

【讨论】:

    【解决方案2】:

    节点 js 代码中缺少您的电子邮件,您必须像这样处理来自 req 的电子邮件常量电子邮件 = req.query.email

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案3】:

    我面临同样的问题。我得到 BSONtype:error 我的代码是

    app.get("/user/:email",  async(req, res)=>{
          const email = req.params.email;
          console.log(email)
          const query = {email : email};
          const result = await usersCollection.findOne(query);
          res.send(result);
        })

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 1970-01-01
      • 2014-09-11
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 2019-07-05
      • 1970-01-01
      相关资源
      最近更新 更多