title: How can I save my image data from front end to Mongoose database using Node.js server
body: <p>I have a back end using node.js and a front end using jquery, javascript, ajax and bootstrap. I want to upload an image from front end and save it to the mongoose database. Here the file is loading successfully and image will be in the location called <strong>/public/img</strong>. But how can I save those image information into the database using an API call.<br>
  Below is my code:</p>
  
  <p><strong>Backend Code Node.js, Mongoose</strong></p>
  
  <p><strong>/server.js</strong></p>
  
  <pre><code>var express =   require("express");
  var multer  =   require('multer');
  var path = require('path');
  var mongoose = require('mongoose');
  var bodyParser = require('body-parser');
  
  var app = express();
     app.appname="photogallery";
  
  //config mongoose
    app.db = mongoose.createConnection('localhost/'+app.appname);
    app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
    app.db.once('open', function () {
    //Storage is all good
    });
  
  //Routes and acl
    var router = express.Router();
    require('./routes')(app, router, passport);
  
  var file_url = '';
  
  var storage =   multer.diskStorage({
    destination: function (req, file, callback) {
      callback(null, 'public/img/');
    },
    filename: function (req, file, callback) {
      callback(null, file.fieldname + '-' + Date.now());
       file_url = file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]
    callback(null, file_url);
    }
  });
  
  var upload = multer({ storage : storage}).single('userPhoto');
  
  app.use(express.static(path.join(__dirname, '/public/')));
  
  app.post('/api/photo',function(req,res){
      upload(req,res,function(err) {
          if(err) {
              return res.end("Error uploading file.");
          }
         // res.end("File is uploaded");
        res.json({error_code:0,err_desc:null,file_url:'img/'+file_url});
        /*Now I want to save this file_url to image_url using api /api/photoGallery, please help me to save these information to the db */ 
      });
  });
  
  //config express
    app.set('secret','thisshouldnotbeinplaintext');
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(passport.initialize());
    app.use(router);
  
  
  app.listen(5050,function(){
      console.log("Working on port 5050");
  });
  </code></pre>
  
  <p><strong>/api/requests.js</strong></p>
  
  <pre><code>'use strict';
    var passport = require('passport');
    var app = require('../app');
  
  exports.init = function(pp) {
      passport = pp;
      app = pp;
      return exports;
  };
  
  exports.root = function(req, res) {
      res.send("Running");
    };
  
  //Add Image Data
  exports.addData = function(req, res) {
    var addData = req.app.db.model('Data');
    var data = {  image_title  : req.body.image_title,
                  image_url    : "http://localhost:5050/"+req.body.image_url
                }
    var query = addData(data);
    query.save(function(err){
      if(err){
        console.log(err.toString());
      }
    console.log('Image Saved Successfully');
    res.json({ success: true });
   });
  };
  </code></pre>
  
  <p><strong>/schema/Data.js</strong></p>
  
  <pre><code>'use strict';
  
  exports = module.exports = function(app, mongoose) {
      var dataSchema = new mongoose.Schema({
          image_title  :  { type: String, unique: true,  lowercase: true },
          image_url    :  { type: String, unique: true,  lowercase: true }
      });
      app.db.model('Data', dataSchema);
  };
  </code></pre>
  
  <p><strong>/models.js</strong></p>
  
  <pre><code>'use strict';
  
  module.exports = function(app, mongoose) {
      //Mongoose Schemas
      require('./schema/Data')(app, mongoose);
  };
  </code></pre>
  
  <p><strong>/routes.js</strong></p>
  
  <pre><code> 'use strict';
  
  module.exports = function(app, router, passport) {
  
      var requests = require('./api/requests').init(passport);
      router.get('/', requests.root);
  
      router.post('/api/addPhoto/v1', requests.addData);
      router.get('/api/getPhoto/v1', requests.getPhoto);
  
  };
  </code></pre>
  
  <p><strong>e.g Json Will Be like below</strong></p>
  
  <pre><code>{
     image_title: exampleImage,
     image_url: xyzscjnscncsl.exampleImage.png
  }
  </code></pre>
  
  <p><strong>Frontend Code Jquery, JavaScript, Ajax, HTML</strong></p>
  
  <p><strong>/public/index.html</strong></p>
  
  <pre><code>&lt;div class="modal fade" id="myModal" role="dialog"&gt;
      &lt;div class="modal-dialog"&gt;
          &lt;!-- Modal content--&gt;
          &lt;div class="modal-content"&gt;
              &lt;div class="modal-header"&gt;
                  &lt;button type="button" class="close" data-dismiss="modal"&gt;&amp;times;&lt;/button&gt;
                  &lt;h4 class="modal-title"&gt;Please Upload Image&lt;/h4&gt;
              &lt;/div&gt;
              &lt;form id="uploadForm" enctype="multipart/form-data" action="/api/photo" method="post"&gt;
              &lt;div class="modal-body"&gt;
                  &lt;div class="form-group"&gt;
                      &lt;input type="text" class="form-control" id="imagetitle" placeholder="Image Title"&gt;
                  &lt;/div&gt;
                   &lt;div class="form-group"&gt;
                       &lt;input type="file" class="form-control" id="input-image" name="userPhoto" accept="image/*"&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="modal-footer"&gt;
                  &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Cancle&lt;/button&gt;
                  &lt;button type="submit" class="btn btn-default" value="Upload Image" name="submit"&gt;Save&lt;/button&gt;
              &lt;/div&gt;
                  &lt;span id = "status"&gt;&lt;/span&gt;
              &lt;/form&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>/public/javascript/image.js</strong></p>
  
  <p>How to save image data from here to the mongoose db using an API call?    </p>
  
  <pre><code>$(document).ready(function() {
      $('#uploadForm').submit(function() { 
          $("#status").empty().text("File is uploading...");
          $(this).ajaxSubmit({
              error: function(xhr) {
                  status('Error: ' + xhr.status);
              },
              success: function(response) {
                  console.log(response)
                  $("#status").empty().text(response);
              }
          });
          return false;
      });    
  });
  </code></pre>