我正在尝试使用nodejs中的multer上传图像。我将multer配置为将上传的图像保存在“upload”目录中,并且在提交表单时,图像将按原样发送到目录。但我正在尝试将该映像的路径(req.file.path)保存到mongodb数据库,这是行不通的。我是nodejs和mongodb的新手,我无法弄清楚问题是什么。 这是我得到的错误:
ObjectParameterError:Document()的参数“obj”必须是一个对象,得到资产\上传\ uploaded_file-1518264794720.jpg at new ObjectParameterError(C:\ xampp \ htdocs \ projets \ NodeApp01 \ node_modules \ mongoose \ lib \ error \ objectParameter.js:23:11) 在model.Document(C:\ xampp \ htdocs \ projets \ NodeApp01 \ node_modules \ mongoose \ lib \ document.js:55:11) 在model.Model(C:\ xampp \ htdocs \ projets \ NodeApp01 \ node_modules \ mongoose \ lib \ model.js:59:12) 在新模型(C:\ xampp \ htdocs \ projets \ NodeApp01 \ node_modules \ mongoose \ lib \ model.js:3750:13)
这是我的index.js:
var express=require('express');
var app=express();
var fs=require('fs');
var multer=require('multer');
app.set('view engine','ejs');
app.use(express.static('assets'));
var mongo=require('mongoose');
mongo.connect('mongodb://username:pass@database...');
var schema=new mongo.Schema({
item:String
});
var model1= mongo.model('todomod',schema);
var storage = multer.diskStorage({
destination: 'assets/uploads/',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+ '.jpg')
}
})
var upload = multer({ storage: storage });
app.get('/',function(request,response){
response.render('index.ejs');
});
app.get('/add_item',function(request,response){
response.render('add_item.ejs');
});
app.post('/add_item',upload.single('uploaded_file'),function(req,res){
console.log(req.body);
console.log(req.file);
model1(req.file.path).save(function(err,data){
if(err) throw err
res.json(data);
})
});
app.listen(80);
console.log('Application listening on port 80....');
这是我对形式的看法(.ejs):
<body>
<% include partials/navigation.ejs %>
<h1>Adding an item to the shop</h1>
<form id="theform" action="add_item" method="POST" enctype="multipart/form-data">
Name of item:<input type="text" name="item" class="thedata"><br>
<br>
Photo of item:<input type="file" name="uploaded_file" class="thefile">
<button type="submit">Add item</button>
</form>
</body>
答案 0 :(得分:0)
问题是你传递的是上传的文件路径而不是文件对象,你可以这样做来保存mongodb上传的文件路径:
let db_data = {
item : req.file.path
};
model1(db_data ).save(function(err,data){
if(err) throw err
res.json(data);
})