I am able to store image path in mongodb.Here I am storing image paths in array format. Using document Id I need to add another image i.e., I want to push another image path into that array.So my question is how can I store another image path in mongodb.
Here I am uploading image using html
file. This is my code index.html
<form id="uploadForm"
enctype="multipart/form-data"
action="/api/file"
method="post"
>
<input type="file" name="userFile"/>
<input type="submit" value="Upload File" name="submit">
</form>
Here is my server code server.js
var express=require('express');
var multer=require('multer');
var bodyParser = require('body-parser');
var Image=require('./models/image');
var Product=require('./models/product');
var mongoose=require('mongoose');
var path = require('path');
var rand;
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var app=express();
var ejs = require('ejs')
app.set('view engine', 'ejs')
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/uploads')
},
filename: function(req, file, callback) {
//callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
//callback(null, file.originalname)
rand=Date.now() + path.extname(file.originalname);
callback(null, file.fieldname + '-' + rand);
}
})
var upload = multer({
storage: storage});
app.get('/api/file',function(req,res){
res.sendFile('E:/saas/nodejs/uploads/db/views/index.html');
});
app.post('/api/file',upload.single('userFile'), function(req, res) {
console.log(req.file);
console.log(req.file.path);
Image.create({imagePaths:[{imagepath:req.file.path}]},function(err,img){
if (err) throw err;
console.log(img);
console.log('Path created!');
var id = img._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the image path with id: ' + id);
});
})
var route=require('./routes/route');
app.use('/route',route);
app.listen(3000,function(){
console.log("Server listening on 3000");
});
After running the server I will use this in browser http://localhost:3000/api/file
using this I am able to upload file and I will get mongodb document id in response.Using this Id how can I upload another image path.