1
我能夠在mongodb.Here中存儲圖像路徑我正在以數組格式存儲圖像路徑。使用文檔ID我需要添加另一個圖像,即我想推入另一個圖像路徑到數組中。所以我的問題是如何在mongodb中存儲另一個圖像路徑。使用nodejs在mongodb中添加另一個圖像路徑
這裏我使用html
文件上傳圖片。這是我的代碼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>
這裏是我的服務器代碼server.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:/saas/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");
});
使用這個我可以上傳文件,我將獲得MongoDB的文件運行,我會在瀏覽器http://localhost:3000/api/file
使用此服務器後ID作爲迴應。使用此ID我怎樣才能上傳另一個圖像路徑。
您可以使用$推。 https://docs.mongodb.com/manual/reference/operator/update/push/ –
@Dinesh在這裏我的路由/ api /服務器代碼中的文件與HTML格式的動作鏈接。有了這個我可以upload.It鏈接與HTML表單。所以我怎麼可以推另一個路線,路線應該找到id,並且必須使上傳文件 –
在路線使ID作爲可選。在服務器端檢查路由中是否存在id,使用$ push更新舊的mongodb文檔。另一個明智的創造新的。爲了使其可選,請參閱https://stackoverflow.com/questions/10020099/express-js-routing-optional-spat-param而不是單個文件,爲什麼不能一次上傳所有圖像? –