2017-08-30 69 views
1

我正在使用node.js,angularjs,& mongoDb。
我正在創建產品上傳頁面。

它分爲兩個部分:
如何在將數據發佈到mongoDb後返回id?

  1. 數據頁:這部分將包含文本框&下拉菜單。
  2. 圖片上傳頁面:這部分會有圖片上傳控制。

所以我想創造同一頁2點的形式,從第一頁,我將發佈文本數據的MongoDB,返回PRODUCT_ID新創建的產品,然後上傳與返回PRODUCT_ID圖像。

我開發了restFul API以發佈產品api/products/create-product
產品型號

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


圖片模型

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


產品控制器(角):

$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; 

    }); 
} 


角前端

<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); 
     }); 



     }); 
    }); 
    } 
}); 

問題

  1. 我是以正確的方式做這件事,還是有另一種更好的方法來做到這一點?
  2. 如果這是正確的方式,那麼我如何發佈獲得發佈product_id,以發佈圖片?
    謝謝。
+1

您也可以在您的客戶端代碼中生成一個新的ID __before__插入。這樣,你不需要得到新的身份證,你已經知道了。 –

+0

如何在將數據推送到mongoDb之前創建'productId'? –

+0

不知道如何在node.js中做到這一點。我敢肯定,這個文件已經涵蓋了。 –

回答

1

這是我的配置文件,它與mongodb進行連接。這是config.js

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

這是我schema's。我創建了兩個集合,一個是products,另一個是images。將這兩個模式保存在models文件夾中。這是我的產品模式我把它命名爲product.js

var mongoose = require('mongoose'); 

var nameSchema = new mongoose.Schema({ 

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

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

這裏是我的圖片模式我把它命名爲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); 

下面是html文件保留此文件夾views。我把它命名爲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> 

下一頁這裏是路線文件保留這個文件中routes文件夾並將其命名爲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; 

下面是服務器端的代碼命名爲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"); 
}); 

運行服務器node app.js

這裏是我的API's發佈產品的詳細信息MongoDB中&後的圖像路徑

  1. 使用POST發佈產品詳細信息的方法使用http://localhost:3000/route/productData。後通過體數據等

{ 「產品名稱」: 「霜」, 「productPrice」:88 }

  • 使用GET方法用於獲取從MongoDB的產品詳情對於使用http://localhost:3000/route/product

  • 現在打開瀏覽器,輸入http://localhost:3000/api/file然後選擇要上傳的文件,點擊提交按鈕,然後你會得到的文件ID在response.Just記下此標識。你將ü爲此,我在Image架構中發佈productId。

  • 當你想從mongodb使用GET方法和使用http://localhost:3000/route/image看到圖像路徑的細節。

  • 現在,您可以使用您在之前獲得的文檔ID在圖像架構中添加productId。對於這種使用PUT方法和使用http://localhost:3000/route/postingImage/59ae2f9195730f1e00be7509在這裏我只是給了我的文檔Id。你需要把你的文檔Id在那裏。並通過身體發送產品ID這樣

    { 「的productId」: 「59a6ac68a87d9f102c4496b8」 }

  • 此之後,你會爲enter image description here

    響應您可以在MongoDB中CHE也。

    1. use image
    2. show collections
    3. db.images.find().pretty();
    4. db.product.find().pretty(); 希望這有助於。
    +0

    感謝你的回答,它真的幫了我很大的忙。 –

    +0

    你知道任何在線編輯器練習MEAN堆棧嗎? –

    +0

    我很高興它有幫助...如果您有任何疑問問我,我嘗試解決它.... –

    0

    5秒到谷歌(沒有測試):

    collection.insert(objectToInsert, function(err){ 
        if (err) return; 
    
        // Object inserted successfully. 
        var objectId = objectToInsert._id; // this will return the id of object inserted 
    }); 
    

    Source

    0

    您可以使用此代碼

    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); 
        });  
    }) 
    

    以同樣的方式發佈產品數據,你可以使用product_id發佈圖像,該產品將在mongodb中添加產品時作爲響應得到。當你想看到的圖像其所屬,那麼你可以傳遞的product_id作爲參數

    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); 
        } 
        }); 
    }); 
    

    如果你需要的任何其他信息,讓我知道。希望這有助於

    +0

    好的,我會嘗試這種方法。 你能幫我把多張圖片上傳到服務器文件夾,並將imagePaths保存到mongoDb中嗎? –

    +0

    我搜索了很多,但找不到任何工作解決方案。我得到的教程將使用** multer **等模塊,但它們只會將圖像保存到文件夾,但不會將imagePaths保存爲貓鼬收藏。 –

    +0

    我會嘗試,我會給我的答案,如果我找到任何... –

    相關問題