我正在输入一个csv文件。由于输入形式为array,因此我将其转换为对象,然后再将其插入mongo数据库。即使数据库已连接(根据终端),也未创建集合,因此也未插入数据。任何帮助表示赞赏。谢谢。
-- Index.js --
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const mongoclient = require('mongodb').MongoClient;
const app = express();
// import the routes
const upload_file = require('./routes/route');
// Use middleware
app.use('/upload',upload_file);
app.use(express.static(__dirname));
app.get('/upload',(req,res)=>{
res.sendFile(path.join(__dirname+'/html/main.html'));
});
// Connect to the database
mongoclient.connect('mongodb://127.0.0.1:27017/',{ useNewUrlParser: true ,useUnifiedTopology: true},(error)=>{
if(error){
console.log('Error in connecting to the database - ',error);
}else{
console.log('Connected to database');
app.listen(8080,()=>{
console.log('Server listening at 8080');
});
}
});
------------------------------------------------------------
-- Schema.js --
//Schema for the MongoDB collection
const mongoose = require('mongoose');
const csv_schema = mongoose.Schema({
Name:{
type: String,
required: true
},
RegNo:{
type: String,
required: true
},
Subject:{
type: String,
required: true
},
Mark:{
type: String,
required: true
}
});
module.exports = mongoose.model('student',csv_schema);
------------------------------------------------------------
-- Route.js --
// Accpets the post request
const express = require('express');
const router = express.Router();
const multer = require('multer');
const upload = multer({dest: '../temp/csv'});
const csv = require('fast-csv');
const student = require('../models/schema');
router.post('/',upload.single('file'),(req,res)=>{
csv.parseFile(req.file.path).on('data',(data)=>{
// Converting the array input to object type
let object = Object.assign({},data);
var student_object = {
Name: object[0],
RegNo: object[1],
Subject: object[2],
Mark: object[3]
};
student.insert(student_object,(err, data)=>{
console.log(data);
if(err)
console.error("Err: ",err);
else
console.log("Successfully created");
});
});
});
// To check whether the data was inserted successfully
router.get('/data',async (req,res)=>{
const data = await student.find();
console.log(data);
});
module.exports = router;
<!DOCTYPE html>
<html>
<head>
<title>CSV upload page</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit"></button>
</form>
</body>
</html>