简体   繁体   中英

How can i get data from Mongodb using mongoose, nodejs

I'm just started learning Nodejs, mongodb, reactjs and having a trouble.

I'm trying to get data from 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.

Edit 1:

You're also querying with mongoose, wrong as it takes the first argument as the query:

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:

this.setState({ data: result.data }, () => {
    console.log(this.state)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM