【问题标题】:How can I get more than one document from mongoDB?如何从 mongoDB 获取多个文档?
【发布时间】:2020-05-09 16:17:45
【问题描述】:

我有 Button 组件,它生成了 16 次,它有 localstate(reactjs) 但我需要通过使用与 mongoDB 的连接使其成为全局的,所以我必须从一个集合中为每个 Button 获取 16 个文档,我没有'不知道我做错了什么.. 我能做到的最好的事情是生成整个集合 16 次或获取一个文档 16 次.. 我怎样才能获取另一个文档?比如第 1、2、3...16。请帮忙

代码:

router.get('/:name', (res, req) => {
const name = req.params.name

console.log('name', name);

 Buttons.find({ name: name})
.then(buttons => res.json(buttons))
.catch(err => res.status(402).send({message: 'error while fetching'})
);
});

以及函数代码:

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

 console.log(getButtons());

【问题讨论】:

  • 请用简单的方式解释你在这里想要达到的目标
  • 哦,对不起。我想为每个组件获取唯一记录。我在 mongoDB 中有文档,例如:名称:button1,名称:button2,名称:button3。我想得到它并稍后将其分配给组件
  • 你用的是猫鼬吧?
  • @Goteii Buttons.findOne() 只会给你一个文档,所以如果你想获取所有按钮,你必须调用 Buttons.find() 它将返回所有按钮然后你可以处理它客户。
  • @PrakashKarena 是的,我使用猫鼬

标签: node.js reactjs database mongodb express


【解决方案1】:

你可以从你的请求中得到你的名字作为参数

router.get('/:name', (res, req) => {

 const name = req.params.name;

  console.log('name',name); // check you are getting name or not ?

 // findOne will find your one document as per your name and return your document is better to use then find 

 Buttons.findOne({ name : name })  
.then(buttons => res.json(buttons))
.catch(err=> res.status(402).send({message : 'error while fetching recored' }))

});

前端

const getButtons = async (name) => {

    let RESULT;

     axios.get('api/buttons/${name}')
      .then( response => { RESULT = response.data } )
      .catch(err => console.log(err));

    console.log('RESULT',RESULT);

    return RESULT;

}


 console.log('data',getButtons('button1'));

现在您可以使用名称 getButtons(your_button_name) 调用此函数,您将根据传递的名称获得按钮响应。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2021-08-17
相关资源
最近更新 更多