我有一个 Button 组件,它生成了 16 次,它有 localstate(reactjs),但我需要通过使用与 mongoDB 的连接来使其成为全局的,所以我必须从每个 Button 的一个集合中获取 16 个文档,我不知道我做错了什么。我能实现的最好的结果是生成整个集合 16 次或获取一个文档 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());
最佳答案
您可以从您的请求中获取您的姓名作为参数
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) 调用此函数,您将根据传递的名称获得按钮响应。
关于node.js - 如何从 mongoDB 获取多个文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59877776/