1

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.

Syed Ayesha Bebe
  • 1,797
  • 1
  • 15
  • 26
  • You can use $push. https://docs.mongodb.com/manual/reference/operator/update/push/ – Dinesh undefined Sep 05 '17 at 05:28
  • @Dinesh here my route /api/file in server code is linked with action in html form.With this I can upload.It is linked with html form .So how can I push with another route that route should find the id and have to make upload file – Syed Ayesha Bebe Sep 05 '17 at 05:32
  • In route make id as optional. In server side check for id in route if it is there, update old mongodb document using $push. other wise create new one. To make it optional refer here https://stackoverflow.com/questions/10020099/express-js-routing-optional-spat-param instead single file at a time, why can't you upload all the images at a time?. – Dinesh undefined Sep 05 '17 at 05:41
  • @dinesh I tried it ..this concept is working on get method.When I change route with optional parameter in both get method route and post method route.There is no change.Image is adding as new document.Will you please tell me how can I do it in my post method – Syed Ayesha Bebe Sep 05 '17 at 07:23

1 Answers1

1

Use $push to store path in array

schemaName.findByIdAndUpdate(
   { req.headers.id },
   { $push: { imagePath: '/newPath' } },
   (err,response)=>{
        if(err){
             console.log(err);
        }

});
MeVimalkumar
  • 3,192
  • 2
  • 15
  • 26