mayank bisht
mayank bisht

Reputation: 874

How to get id back, after posting data to mongoDb?

I am using node.js, angularjs, & mongoDb.
I am creating a product upload page.

It is divided into 2 parts:

  1. Data page: This part will contain, textfields & dropdowns.
  2. Image Upload page: This part will have image upload control.

So I thought to create 2 forms in same page, from first page i will post text data to mongoDb, return product_id of the newly created product, and then upload images with returned product_id.

I have developed restFul API to post product api/products/create-product.
Product model :

{
productName:{type: String},
productPrice:{type: Number}
}


Image model:

{
productId:{type: String},
imagePaths:[{type: Array}]
}


Product Controller(Angular):

$scope.newProduct = function(){
      var formData = new FormData;
      for(key in $scope.product){
        formData.append(key, $scope.product[key]);
      } 
  //getting the files
  var file = $('#file')[0].files[0];
  formData.append('image', file);

  //Post data
  $http.post('http://localhost:3000/products/api/new-product',formData,{
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
  }).then(function(res){
    $scope.item = res.data;

  });
}


Angular front-end

<input type="text" class="form-control" ng-model="product.productName" placeholder="Enter Product Name">
<input type="file" multiple="multiple" id="file" >
<button type="submit" ng-click="newProduct()" class="btn btn-primary">Add Product</button>


POST API

router.post('/api/new-product',upload.any(),function(req, res, next){

  var pro = req.body;
  if(req.files){
    req.files.forEach(function(file){

      var filename = (new Date()).valueOf() + '-' + file.originalname;
      fs.rename(file.path,'public/images/'+ filename, function(err){
        if (err) throw err;
        //Save to mongoose

      var product = new Products({
          productName: req.body.productName
         });
          product.save(function(err, result){
          if(err){ throw err}
            res.json(result);
        });



      });
    });
  }
});

Questions:

  1. Am I doing this correct way, or there is another better way for doing this?
  2. If this is correct way, then how can I post get posted product_id, in order to post images?
    Thanks.

Upvotes: 1

Views: 5416

Answers (3)

Syed Ayesha Bebe
Syed Ayesha Bebe

Reputation: 1448

Here is my config file which makes connection with mongodb. This is config.js

module.exports = {
    'secretKey': '12345-67890-09876-54321',
    'mongoUrl' : 'mongodb://localhost:27017/image'
}

Here is my schema's. I created two collections one is products and another is images. Keep these two schemas in models folder. Here is my product schema I named it as product.js

var mongoose = require('mongoose');

var nameSchema = new mongoose.Schema({

productName:{type: String},
productPrice:{type: Number}

});
module.exports  = mongoose.model("product", nameSchema);

Here is my images schema I named it as image.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imagepath:{
    type:String,
    required:true
}
});
var nameSchema = new Schema({
 productId:{type: String},
imagePaths:[imageSchema]
});
module.exports  = mongoose.model("image", nameSchema);

Here is html file keep this file in views folder. I named it as 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>

Next here is routes file keep this file in routes folder and named it as route.js.

var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var Image = require('../models/image');
var Product = require('../models/product');
var app = express();
var Router = express.Router();
Router.use(bodyParser.json());

Router.get('/product',function(req,res){
 Product.find({}, function (err, product) {
        if (err) throw err;
        res.json(product);
    });
})  
Router.post('/productData',function(req, res, next){
    Product.create(req.body, function (err, product) {
        if (err) throw err;
        console.log('Product Data created!');
        var id = product._id;

        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        res.end('Added the product data with id: ' + id);
    });    
})
Router.put('/postingImage/:Id',function(req,res,next){
 Image.findByIdAndUpdate(req.params.Id, {
        $set: req.body
    }, {
        new: true
    }, function (err, batch) {
        if (err) throw err;
        res.json(batch);
    });
})

Router.get('/image',function(req,res){
 Image.find({}, function (err, img) {
        if (err) throw err;
        res.json(img);
    });
})  
    module.exports = Router;

Here is server code named it as app.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:/syed ayesha/nodejs/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");
});

Run the server as node app.js

Here are my API's to post product details & post image path in mongodb

  1. Use POST method for posting product details use http://localhost:3000/route/productData. Post the data through body like

{ "productName":"cream", "productPrice":88 }

  1. Use GET method for getting the product detials from mongodb for that use http://localhost:3000/route/product

  2. Now open browser and type http://localhost:3000/api/file then choose a file to upload click on submit button then you will get document Id in response.Just make a note of this Id .You will use this I for posting productId in Image schema.

  3. When you want to see the image path details from mongodb use GET method and use http://localhost:3000/route/image.

  4. And now you can add productId in image schema using the document Id that you got in previous. For this use PUT method and use http://localhost:3000/route/postingImage/59ae2f9195730f1e00be7509 here I just I gave my document Id .You need to put your document Id there. And send the productId through body like this

    { "productId":"59a6ac68a87d9f102c4496b8" }

After this you will the response as enter image description here

You can che in mongodb also .

  1. use image
  2. show collections
  3. db.images.find().pretty();
  4. db.product.find().pretty(); Hope this helps.

Upvotes: 0

Syed Ayesha Bebe
Syed Ayesha Bebe

Reputation: 1448

You can post the product data using this code

app.post('/productData',function(req, res, next){
    Product.create(req.body, function (err, product) {
        if (err) throw err;
        console.log('Product Data created!');
        var id = product._id;

        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        res.end('Added the product data with id: ' + id);
    });    
})

In the same way you can post the image using the product_id that will get as response when the product is added in mongodb. When you want to see the image to which it belongs then you can pass the product_id as parameter

app.get('/productImage/:productId',function(req,res,next){
Image.find({"product_id":req.params.productId}, function (err, data) {
    if(err) console.log("error");
    if(data==true){
        res.json(batch);
    }
    });
});

If you want any other information let me know. Hope this helps

Upvotes: 0

MrWook
MrWook

Reputation: 348

5sec into google (didn't test it):

collection.insert(objectToInsert, function(err){
   if (err) return;

   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

Source

Upvotes: 2

Related Questions