当我使用以下代码运行“ node testMongoDB.js”时,我可以在本地Mongo数据库中插入一行。因此,这有望证明我的数据库已安装,正常工作并且连接字符串正确。运行数据后,我可以看到存储在数据库中的数据。 我正在做一个最小的“概念验证”(没有用户安全性),以允许某人上传文件,例如CSV(逗号分隔值)。然后,我将对其进行解析并将行存储在数据库中。
但是当我将相同的代码放入React应用程序中并执行“ npm start”时,我在连接上收到错误:
MongoNetworkError:无法连接到服务器[localhost:27017] 首先连接[TypeError:net.createConnection不是函数]
完整错误出现在下面的两个代码示例之后。
testMongoDB.js代码:
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()
})
反应代码(app.js)[我已经分别测试了解析文件并使其正常工作,所以下一步是将行存储在数据库中]:
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;
react中的错误(当我将文件拖放到网页上时触发)。
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)
答案 0 :(得分:1)
在这里,您正在使用onLoad
方法内部的数据库服务器进行连接。理想情况下,数据库连接应该已经启动,并且您应该进行数据库交互。不建议一次又一次地创建新的连接,这不是处理此问题的理想方法。您只需使用简单的节点服务器并通过它与数据库连接即可。为了进行正确的渲染,您的前端代码应该不那么繁重,简洁明了。