首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何制作用于电子邮件的查询api,使我能够找到数据电子邮件智能为不同的用户从mongoDB与高速公路,nodeJs

如何制作用于电子邮件的查询api,使我能够找到数据电子邮件智能为不同的用户从mongoDB与高速公路,nodeJs
EN

Stack Overflow用户
提问于 2022-05-02 11:10:36
回答 2查看 138关注 0票数 1

我是新的后端开发与MongoDB,NodeJS和前端开发与反应-JS。我想做一个API端点,当用户登录到系统时,它可以从MongoDB查找数据,并通过用户电子邮件地址进行筛选。我的登录系统完全没问题。但问题是,当我试图从客户端检索数据时,时间数据并没有在UI上显示(获取)。它会创建和空数组。我想知道我的代码有什么问题。

这里是我的后端API代码:

代码语言:javascript
复制
app.get('/myproducts', async (req, res) => {
  const email = req.query.email;
  const query = { email: email };
  const cursor = inventoryCollection.find(query);
  const myProducts = await cursor.toArray();
  console.log(myProducts);
  res.send(myProducts);
});

客户端代码:

代码语言:javascript
复制
useEffect(() => {
  const getMyProducts = async () => {
    const email = user?.email;
    console.log(email);
    const url = `http://localhost:5000/myproducts?email=${email}`;
    try {
      await fetch(url)
        .then(res => res.json())
        .then(data => setProducts(data))
    } catch (error) {
      console.log(error?.message)
    }
  }
  getMyProducts();
}, [user])
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-02 19:39:37

我解决了,我犯了个错误。当我在我的库存中添加产品时,我没有将我的电子邮件保存在数据库中。将我的电子邮件保存在数据库中后,现在我可以通过电子邮件过滤产品并在UI上显示。

代码语言:javascript
复制
    const handleProductPost = (event) => {
    event.preventDefault();
    const email = user.email; //before, I did not added this email when posting 
    const productName = event.target.productName.value;
    const image = event.target.image.value;
    const description = event.target.description.value;
    const price = event.target.price.value;
    const quantity = event.target.quantity.value;
    const supplierName = event.target.supplierName.value;

    const product = { email, productName, image, description, price, quantity, supplierName };

    fetch('https://back-pack-warehouse.herokuapp.com/product', {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify(product)
    })
        .then(res => res.json())
        .then(data => {
            if (data.insertedId) {
                toast('Product Added Successfully');
                event.target.reset();
            }
        });
}
票数 1
EN

Stack Overflow用户

发布于 2022-05-02 13:19:28

toArray函数存在于本机MongoDB NodeJS驱动程序的游标类上。MongooseJS中的查找方法返回一个查询对象。

在这种情况下,您可以直接使用cursor记录或发送res.send(cursor)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72085840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档