這是我的配置文件,它與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中&後的圖像路徑
- 使用
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」 }
此之後,你會爲
響應您可以在MongoDB中CHE也。
use image
show collections
db.images.find().pretty();
db.product.find().pretty();
希望這有助於。
您也可以在您的客戶端代碼中生成一個新的ID __before__插入。這樣,你不需要得到新的身份證,你已經知道了。 –
如何在將數據推送到mongoDb之前創建'productId'? –
不知道如何在node.js中做到這一點。我敢肯定,這個文件已經涵蓋了。 –