[英]How can i get data from Mongodb using mongoose, nodejs
I'm just started learning Nodejs, mongodb, reactjs and having a trouble.我刚开始学习 Nodejs、mongodb、reactjs 并且遇到了麻烦。
I'm trying to get data from mongodb.我正在尝试从 mongodb 获取数据。
backend code:后台代码:
app.post('/tweet',(req,res)=>{
tweetData.find((err,data)=>{
if(err){
return res.json({success: false, error: err});
}
return res.json({success: true, data:data});
});
})
font end code:字体结束代码:
class TweetContainer extends React.Component{
constructor(props){
super(props);
this.state = {
data:null,
API_URL : 'http://localhost:5000/tweet'
}
}
componentDidMount(){
fetch(this.state.API_URL)
.then(response=>response.json)
.then(result=>{
this.setState({
data: result.data
});
console.log(this.state.data)
});
}
render(){
return(
<div id="main">
<h2>Tweet</h2>
<div id="stream">
</div>
</div>
);
}
}
when i log the data, console show undefined.当我记录数据时,控制台显示未定义。
What i'm doing wrong.我做错了什么。
You're also querying with mongoose, wrong as it takes the first argument as the query:您也在使用 mongoose 进行查询,这是错误的,因为它将第一个参数作为查询:
app.post('/tweet',(req,res)=>{
tweetData.find(queryObject || {}, (err,data)=>{
if(err){
return res.json({success: false, error: err});
}
return res.json({success: true, data:data});
});
})
You're logging the state immediately after you're updating it, let me tell you that's not how it works, it doesn't immediately update the state, so you have to wait for it to do.您在更新状态后立即记录状态,让我告诉您这不是它的工作原理,它不会立即更新状态,因此您必须等待它完成。
You can pass a callback to setState
, so that it executes the callback after the state change has been completed, something like this:您可以将回调传递给
setState
,以便它在状态更改完成后执行回调,如下所示:
this.setState({ data: result.data }, () => {
console.log(this.state)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.