-> Mongodb Tutorial to store unstructured data <-
-> Start the mongodb server
-> Start the client and create uploadDB database and collection in it 'files'
-> Download visual studio code
-> create index.html file for front end.
--> index.html
<html>
<head>
<title>Upload files</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="text" name="name" placeholder="file name.." /> <br />
<input type="file" name="uploadedfile"/> <br /> <br />
<input type="submit" value="Upload File" /></form>
<form action="/download" method="GET">
<input type="submit" value="Download File" />
</form>
</body>
</html>
-> go to the folder -> git bash
$ npm install express express-fileupload mongodb fs --save
-> Also download nodejs and install it, if not installed
-> create javascript file(index.js)
const express = require('express')
const fileUpload = require('express-fileupload')
const mongodb = require('mongodb')
const fs = require('fs')
const app = express()
const router = express.Router()
const mongoClient = mongodb.MongoClient
const binary = mongodb.Binary
router.get("/", (req, res) => {
res.sendFile('./index.html', { root: __dirname })
})
router.get("/download", (req, res) => {
getFiles(res)
})
app.use(fileUpload())
router.post("/upload", (req, res) => {
let file = { name: req.body.name, file: binary(req.files.uploadedfile.data) }
insertFile(file, res)
})
function insertFile(file, res) {
mongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, (err, client) => {
if (err) {
return err
else {
let db = client.db('uploadDB') // give the name as per database created
let collection = db.collection('files') // give the name as per collection created
try {
collection.insertOne(file)
console.log('File Inserted')
catch (err) {
console.log('Error while inserting:', err)
client.close()
res.redirect('/')
})
}
function getFiles(res) {
mongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, (err, client) => {
if (err) {
return err
else {
let db = client.db('uploadDB') // give the name as per database created
let collection = db.collection('files') // give the name as per collection created
collection.find({}).toArray((err, doc) => {
if (err) {
console.log('err in finding doc:', err)
else {
let buffer = doc[0].file.buffer
fs.writeFileSync('uploadedImage.jpg', buffer)
})
client.close()
res.redirect('/')
})
}
app.use("/", router)
app.listen(3000, () => console.log('Started on 3000 port'))
-----------------------------------------------------------------------------------------------------------------
-> Open git bash in created folder
nodemon index.js
-> Open google -> http://localhost:3000
upload file
file will be inserted
-> cmd -> mongo console
db.files.find({}) // will give the fine in base24 code