title: React MongoDB MongoNetworkError: failed to connect to server on first connect [TypeError: net.createConnection is not a function]
body: <p>When I run &quot;node testMongoDB.js&quot; 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 &quot;proof of concept&quot; (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.</p>
  <p>But when I put the same code in a React application, and do &quot;npm start&quot;, I get an error on the connection:</p>
  <blockquote>
  <p>MongoNetworkError: failed to connect to server [localhost:27017] on
  first connect [TypeError: net.createConnection is not a function]</p>
  </blockquote>
  <p>The full error is after the two code samples below.</p>
  <p>testMongoDB.js code:</p>
  <pre><code>console.log(&quot;Test MongoDB Connect and InsertOne&quot;)
  
  const MongoClient = require('mongodb').MongoClient
  const assert = require('assert')
  const databaseUrl = &quot;mongodb://localhost:27017/&quot;
  const databaseName = 'ShedCompanyPOC'
  const collectionName = &quot;filedata&quot;
  
  MongoClient.connect(databaseUrl, function(err, db) {
     if (err) throw err; 
     var dbo = db.db(databaseName)
     console.log(&quot;About to try the insertOne&quot;)
     dbo.collection(collectionName).insertOne({
         Employeeid: 4,
         EmployeeName: &quot;NewEmployee&quot;
     })
     console.log(&quot;MongoDB InsertOne completed&quot;)
     process.exit()
   })
  </code></pre>
  <p>React code (app.js) [I have separately tested parsing the file and got that working, so next step was to store rows in database]:</p>
  <pre><code>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 &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.
    // const [files, setFiles] = useState([])
    const currDateTime1 = new Date().toISOString()
    console.warn(currDateTime1 + &quot; Starting React/App: function App()&quot;)
    const onDrop = useCallback(acceptedFiles =&gt; {
      // Do something with the files 
      const currDateTime2 = new Date().toISOString()
      console.log(currDateTime2 + &quot; trying to read file&quot;)
      acceptedFiles.forEach((file) =&gt; {
        const reader = new FileReader() 
        reader.onabort = () =&gt; console.log('file reading was aborted')
        reader.onerror = () =&gt; console.log('file reading has failed')
        reader.onload = (data) =&gt; {
             // Do what you want with the file contents 
             //console.log(&quot;file size:&quot;, data.length);
             //const binaryStr = reader.result 
             //const fileContents = reader.readAsText
             const fileContents = data.target.result 
             const currDateTime3 = new Date().toISOString()
             console.log(currDateTime3 + &quot; Text print of file contents:&quot;)
             console.log(fileContents)
             // get MongoDB all set up 
             const MongoClient = require('mongodb').MongoClient
             const assert = require('assert')
             const databaseUrl = &quot;mongodb://localhost:27017&quot;
             const databaseName = 'ShedCompanyPOC'
             const collectionName = &quot;filedata&quot;
             
             MongoClient.connect(databaseUrl, function(err, db) {
              if (err) throw err; 
              var dbo = db.db(databaseName)
              console.log(&quot;About to try the insertOne&quot;)
              dbo.collection(collectionName).insertOne({
                  Employeeid: 5,
                  EmployeeName: &quot;TestEmployee&quot;
              })
              console.log(&quot;MongoDB InsertOne completed&quot;)
            })
  
             /*  This is what I really want to do when I get 
                 the above easy MongoDB working 
  
             MongoClient.connect(databaseUrl, function (err, dbClient) {
                console.log(&quot;First line of mongoClient&quot;)
                if (err) throw err; 
                var dbo = dbClient.db(databaseName)
                console.log(&quot;Connected successfully to MongoDB Server &quot;)
                //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(&quot;Line=&quot; + linecount + &quot; Data=&quot; + line )
                      bulkDb.insert({&quot;line&quot;: line})
                  }
                bulkDb.execute() 
                console.log(&quot;//End of file&quot;)
                dbClient.close()
            })
            */ 
            
          }
        reader.readAsText(file)
      })
    }, [])
    const {getRootProps, getInputProps, isDragActive} = useDropzone ({onDrop}) 
  
    return (
      &lt;div className=&quot;App&quot; {...getRootProps()}&gt;
        &lt;header className=&quot;App-header&quot;&gt;
          &lt;img src={logo2} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;
        &lt;/header&gt;
        &lt;input {...getInputProps()} /&gt;
        {
          isDragActive ? 
            &lt;p&gt;Drop the files here ...&lt;/p&gt; : 
            &lt;p&gt;Drag and Drop a file here, or click to select files&lt;/p&gt;
        }
        &lt;p /&gt;&lt;p /&gt;&lt;p /&gt;&lt;p /&gt;&lt;p /&gt;&lt;p /&gt;
        Thanks for using our company!
      &lt;/div&gt;
      
        );
  }
  
  export default App;
  </code></pre>
  <p>The error in react (which is triggered when I drop a file on the web page).</p>
  <pre><code>error.js:36 Uncaught MongoNetworkError: failed to connect to server [localhost:27017] on first connect [TypeError: net.createConnection is not a function]
      at Pool.&lt;anonymous&gt; (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)
  </code></pre>