how to connect mongodb with react js code example

Example 1: how to connect mongodb with node js

async function main(){
    /**
     * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
     * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
     */
    const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
 

    const client = new MongoClient(uri);
 
    try {
        // Connect to the MongoDB cluster
        await client.connect();
 
        // Make the appropriate DB calls
        await  listDatabases(client);
 
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

main().catch(console.error);

Example 2: how to sent react from data in mongodb

handleSubmit(){
    let databody = {
        "name": this.state.nameIn,
        "quote": this.state.quoteIn
    }

    return fetch('http://localhost:5002/stored', {
        method: 'POST',
        body: JSON.stringify(databody),
        headers: {
            'Content-Type': 'application/json'
        },
    })
    .then(res => res.json())
    .then(data => console.log(data)); 
}


render(){
    return (
        <div>
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name
                    <input type="text" name="name" value={this.nameIn} onChange={this.handleNameChange}/>
                </label>
                <label>
                    quote
                    <input type="text" name="quote" value={this.quoteIn} onChange={this.handleQuoteChange}/>
                </label>
                <input type="submit" value="Add to DB" />
            </form> 
        </div>
    );
}

Example 3: how to sent react from data in mongodb

app.post('/stored', (req, res) => {
    console.log(req.body);
    db.collection('quotes').insertOne(req.body, (err, data) => {
        if(err) return console.log(err);
        res.send(('saved to db: ' + data));
    })
});

Example 4: how to connect mongodb and nodejs

const {MongoClient} = require('mongodb');

Tags:

Go Example