Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple connection to mongodb in react app

I have created simple react app using 'create-react-app'. This app contains form, validation and bootstrap things. Nothing fancy yet works like a charm.

I have also signed up to mongo to get a free cluster so I can send over some data to. So I have this URL:

mongodb+srv://matt:[email protected]/test

Now, all I want to do is to send JSON data from the form to mongo but I don't know how.

When I am following tutorials and installing MongoDB, mongoose or whatever packages and adding basic setup for future CRUD operations:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb+srv://mattOsuch:[email protected]/test';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  db.close();
});

The entire application crashes:

./node_modules/mongodb-core/lib/uri_parser.js
Module not found: Can't resolve 'dns' in 'C:\Users\Mateusz\Desktop\brainhub\node_modules\mongodb-core\lib'

I used to send data using jQuery or mysql_query in PHP but I can't overcome this problem. In other words I want to achieve functionality like presented in this video: https://www.youtube.com/watch?v=Jsqz5op4fH8 So as I said, simple data update.

My suspicion is that react-scripts server listener has some sort of conflict with mongo but I am not sure.

Please help me because I am loosing my nerves.

like image 641
Mateusz Osuch Avatar asked Apr 05 '18 19:04

Mateusz Osuch


People also ask

How does React application connect to MongoDB?

First, we create a react app, and then for backend maintenance, we create API in node. js and express. js which is running at a different port and our react app running at a different port. for connecting React to the database (MongoDB) we integrate through API.


1 Answers

You are using node.js so start server app try using express routing here is a link to a tutorial https://zellwk.com/blog/crud-express-mongodb or https://codeburst.io/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073 or try doing a google search(node.js mongodb and express).

Then when returning a request from server send the data required then use your react client to handle the data recived

like image 71
Santhosh S Kashyap Avatar answered Sep 23 '22 22:09

Santhosh S Kashyap