Such a problem that when I try to simply connect mongoDB in react
import React, {Component} from 'react';
export default class App extends Component{
componentDidMount(){
const {MongoClient} = require('mongodb');
const client = new MongoClient('mongodb srv://dafu4k:****@cluster0.jd26aac.mongodb.net/?retryWrites=true&w=majority');
const start = async () => {
try{
await client.connect();
console.log('Connected')
}
catch(e){
console.log(e)
}
}
start();
}
render(){
return (
<>
<h1>Home page</h1>
</>
)
}
}
Errors of the same type appear in the browser itself
Module not found: Error: Can't resolve 'os' in 'C:\Users\DaFu4\OneDrive\Рабочий >стол\mongotest\mongo-test\node_modules\ip\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "os": require.resolve("os-browserify/browser") }'
- install 'os-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "os": false }
They differ in that the last line has different keys (timers
,crypto
,http
, etc.)
I watched how to connect mongoDB to react, everywhere they used a certain mongoose along with mongoDB, but I can’t understand, maybe it’s required to connect to react, or am I still doing something wrong? (in normal js everything works fine, the code has not changed)
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
package.json
{
"name": "mongo-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"crypto-browserify": "^3.12.0",
"mongodb": "^4.7.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
CodePudding user response:
We can not connect React JS to MongoDB because things don’t work like this. 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.
Check this link:
[1]: https://www.geeksforgeeks.org/how-to-connect-mongodb-with-reactjs/#:~:text=First, we create a react,MongoDB) we integrate through API.