这是我与 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。通过像 这样的正文发布数据
{
“产品名称”:“奶油”,
“产品价格”:88
}
使用GET 方法从mongodb 获取产品详细信息,用于http://localhost:3000/route/product
现在打开浏览器并输入http://localhost:3000/api/file 然后选择要上传的文件单击提交按钮然后您将获得文档 ID 作为响应。只需记下此 ID。您将使用此 I 发布 productId图像架构。
当您想从 mongodb 中查看图像路径详细信息时,请使用 GET 方法并使用 http://localhost:3000/route/image。
-
现在您可以使用之前获得的文档 ID 在图像架构中添加 productId。为此使用PUT 方法并在此处使用http://localhost:3000/route/postingImage/59ae2f9195730f1e00be7509 我只是给了我的文档ID。您需要将文档ID 放在那里。并像这样通过正文发送productId
{
“productId”:“59a6ac68a87d9f102c4496b8”
}
在此之后,您将回复为
你也可以在 mongodb 中 che。
use image
show collections
db.images.find().pretty();
-
db.product.find().pretty();
希望这会有所帮助。