Reputation: 18197
When I run "node testMongoDB.js" with the following code, I'm able to insert a row into my local Mongo database. So this hopefully proves my database is installed, working and the connection string is correct. I am able to see the data stored in the database after running it. I'm doing a minimal "proof of concept" (no user security) to allow someone to upload a file, example a CSV (comma-separated value). I will then parse it and store rows in the database.
But when I put the same code in a React application, and do "npm start", I get an error on the connection:
MongoNetworkError: failed to connect to server [localhost:27017] on first connect [TypeError: net.createConnection is not a function]
The full error is after the two code samples below.
testMongoDB.js code:
console.log("Test MongoDB Connect and InsertOne")
const MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const databaseUrl = "mongodb://localhost:27017/"
const databaseName = 'ShedCompanyPOC'
const collectionName = "filedata"
MongoClient.connect(databaseUrl, function(err, db) {
if (err) throw err;
var dbo = db.db(databaseName)
console.log("About to try the insertOne")
dbo.collection(collectionName).insertOne({
Employeeid: 4,
EmployeeName: "NewEmployee"
})
console.log("MongoDB InsertOne completed")
process.exit()
})
React code (app.js) [I have separately tested parsing the file and got that working, so next step was to store rows in database]:
import React, {useCallback} from 'react';
import {useDropzone} from 'react-dropzone' // use hooks
import logo2 from './images/demo-logo.png'; // demo logo
import './App.css';
function App() {
// Edit <code>src/App.js</code> and save to reload.
// const [files, setFiles] = useState([])
const currDateTime1 = new Date().toISOString()
console.warn(currDateTime1 + " Starting React/App: function App()")
const onDrop = useCallback(acceptedFiles => {
// Do something with the files
const currDateTime2 = new Date().toISOString()
console.log(currDateTime2 + " trying to read file")
acceptedFiles.forEach((file) => {
const reader = new FileReader()
reader.onabort = () => console.log('file reading was aborted')
reader.onerror = () => console.log('file reading has failed')
reader.onload = (data) => {
// Do what you want with the file contents
//console.log("file size:", data.length);
//const binaryStr = reader.result
//const fileContents = reader.readAsText
const fileContents = data.target.result
const currDateTime3 = new Date().toISOString()
console.log(currDateTime3 + " Text print of file contents:")
console.log(fileContents)
// get MongoDB all set up
const MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const databaseUrl = "mongodb://localhost:27017"
const databaseName = 'ShedCompanyPOC'
const collectionName = "filedata"
MongoClient.connect(databaseUrl, function(err, db) {
if (err) throw err;
var dbo = db.db(databaseName)
console.log("About to try the insertOne")
dbo.collection(collectionName).insertOne({
Employeeid: 5,
EmployeeName: "TestEmployee"
})
console.log("MongoDB InsertOne completed")
})
/* This is what I really want to do when I get
the above easy MongoDB working
MongoClient.connect(databaseUrl, function (err, dbClient) {
console.log("First line of mongoClient")
if (err) throw err;
var dbo = dbClient.db(databaseName)
console.log("Connected successfully to MongoDB Server ")
//const clientDb = client.db(databaseName)
var bulkDb = dbo.collection(collectionName).initializeUnorderedBulkOp();
// now process line by line
const lines = fileContents.split(/\r\n|\n/);
var linecount = 0
var line
for (line of lines) {
linecount++
console.log("Line=" + linecount + " Data=" + line )
bulkDb.insert({"line": line})
}
bulkDb.execute()
console.log("//End of file")
dbClient.close()
})
*/
}
reader.readAsText(file)
})
}, [])
const {getRootProps, getInputProps, isDragActive} = useDropzone ({onDrop})
return (
<div className="App" {...getRootProps()}>
<header className="App-header">
<img src={logo2} className="App-logo" alt="logo" />
</header>
<input {...getInputProps()} />
{
isDragActive ?
<p>Drop the files here ...</p> :
<p>Drag and Drop a file here, or click to select files</p>
}
<p /><p /><p /><p /><p /><p />
Thanks for using our company!
</div>
);
}
export default App;
The error in react (which is triggered when I drop a file on the web page).
error.js:36 Uncaught MongoNetworkError: failed to connect to server [localhost:27017] on first connect [TypeError: net.createConnection is not a function]
at Pool.<anonymous> (http://localhost:3000/static/js/0.chunk.js:67734:35)
at Pool.emit (http://localhost:3000/static/js/0.chunk.js:38821:5)
at http://localhost:3000/static/js/0.chunk.js:57221:14
at http://localhost:3000/static/js/0.chunk.js:57632:11
at http://localhost:3000/static/js/0.chunk.js:55228:7
at callback (http://localhost:3000/static/js/0.chunk.js:55447:5)
at makeConnection (http://localhost:3000/static/js/0.chunk.js:55461:12)
at connect (http://localhost:3000/static/js/0.chunk.js:55226:3)
at createConnection (http://localhost:3000/static/js/0.chunk.js:57621:3)
at Pool.connect (http://localhost:3000/static/js/0.chunk.js:57212:3)
at Server.connect (http://localhost:3000/static/js/0.chunk.js:67797:15)
at Server.connect (http://localhost:3000/static/js/0.chunk.js:84152:25)
at createServer (http://localhost:3000/static/js/0.chunk.js:79102:10)
at http://localhost:3000/static/js/0.chunk.js:79031:14
at parseConnectionString (http://localhost:3000/static/js/0.chunk.js:69648:3)
at connect (http://localhost:3000/static/js/0.chunk.js:78977:3)
at http://localhost:3000/static/js/0.chunk.js:77038:5
at maybePromise (http://localhost:3000/static/js/0.chunk.js:85970:3)
at MongoClient.connect (http://localhost:3000/static/js/0.chunk.js:77035:10)
at Function.MongoClient.connect (http://localhost:3000/static/js/0.chunk.js:77255:22)
at FileReader.reader.onload (http://localhost:3000/static/js/main.chunk.js:171:21)
Upvotes: 0
Views: 316
Reputation: 550
Here you are connecting with the database server inside the onLoad
method. Ideally that DB connection should be initiated already and you are supposed to do the DB interaction. Creating new connections, again and again, is not recommended and that is not the ideal way to handle this. you simply can use simple node server and connect with DB through that. Your front-end code should be less heavy, cleaner and simple in order to do the proper rendering.
Upvotes: 1