如何从数据库中为每个组件获取一个唯一数据?

Posted

技术标签:

【中文标题】如何从数据库中为每个组件获取一个唯一数据?【英文标题】:How can I get one single unique data from Database for each one component? 【发布时间】:2020-05-05 02:19:12 【问题描述】:

我必须为每个单独的组件从 mongoDB 获取一条唯一记录。就我而言:对于组件 1,我想从数据库中获取第一个文档,对于组件 2,我想在 16 日之前获取第二个文档。

代码:

router.get('/:name', (res, req) => 
 Buttons.findOne()
sort(name : 1)
.then(buttons => res.json(buttons))
);

以及函数代码:

  async function getButtons() 
try 
const response = await axios.get('api/buttons/:name');
console.log(response);
catch (error) 
console.log(error)


【问题讨论】:

【参考方案1】:

要发送带有变量的请求,您需要执行如下操作

async function getButtons(name) 
     try 
        const response = await axios.get('api/buttons/'+name);
        console.log(response);
     
     catch (error) 
        console.log(error)
     

async function getButtons(name) 
     try 
        const response = await axios.get(`api/buttons/$name`);
        console.log(response);
     
     catch (error) 
        console.log(error)
     


在 getButtons(count) 中传递您的组件计数

当发送请求时将你的变量添加到 url

【讨论】:

嗨!感谢您的回答,但遗憾的是这对我来说不太好。我想我们误解了。我现在生成了 16 个请求,因为我在使用了 16 次的组件中使用了这个请求并且它工作正常,但我想让它从数据库中给我 16 条不同的记录。现在我在 console.log 中显示了第一条记录 16 次,这很糟糕,因为我想将数据库中的数据分配给前端

以上是关于如何从数据库中为每个组件获取一个唯一数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 laravel 中为每个用户生成唯一的自动增量值并将其添加到数据库中

如何从访问数据库列中获取每个唯一值并添加到组合框项目

在 R 中,当 ID 不唯一时,如何从每个 ID 的数据框中获取倒数第二行? [复制]

如何使用 laravel 在引导模式中为每个 id 获取动态数据?

如何从父级获取数据到子级?

如何从firebase数据库中获取数据列表?