how to connect mongodb with react js code example
Example 1: how to connect mongodb with node js
async function main(){
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
await client.connect();
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');