在创建要添加到MongoDB的新对象时,我的要求之一是使用multer将图像文件上传到服务器。映像已成功上传到本地存储库,并生成了文件路径。我正在尝试通过Pictures数组将生成的文件路径保存到mongodb,但是无法发布文件路径数组。
我已经用谷歌搜索了这个问题,但是找不到解决方法。
当前正在运行带有multer 1.4.1的Angular 5,Mongo db v3.6.3。我正在使用Node.js作为我的服务器。
这是架构:
var FiguredataSchema = new mongoose.Schema({
name: {type: String, required: true},
releasedate: {type: Date, required: true},
announcedate: {type: Date},
brand: {type: String, required: true},
series: {type: String, required: true},
number: {type: Number},
manufacturer: {type: String},
distributor: {type: String},
releaseprice: {type: Number},
currencytype: {type: String, default: "USD"},
notes: {type: String},
pictures: {type: Array},
thumbnail: {type: String}
},{timestamps: true});
这是POST路径:
app.post('/add', upload.array("uploads[]",10), function(request, response){ //ADD FIGURE TO DB
var dict = request.files;
var name = request.body.name;
var releasedate = request.body.releasedate;
var announcedate = request.body.announcedate;
var brand = request.body.brand;
var series = request.body.series;
var number = request.body.number;
var manufacturer = request.body.manufacturer;
var distributor = request.body.distributor;
var releaseprice = request.body.releaseprice;
var currencytype = request.body.currencytype;
var notes = request.body.notes;
if(request.files == null){
console.log("errortype", request)
}
else{
console.log("else")
var newfigure = new Figuredata(
{
name: name,
releasedate: releasedate,
announcedate: announcedate,
brand: brand,
series: series,
number: number,
manufacturer: manufacturer,
distributor: distributor,
releaseprice: releaseprice,
currencytype: currencytype,
notes: notes,
pictures: []
}
)
for(var i = 0; i < dict.length; i++){
for(var key in dict[i]){
if(key == "path"){
newfigure.pictures.push(dict[i][key]);
}
}
}
console.log("log",newfigure.pictures)
newfigure.save(function(error){
if(error){
response.json({message: "Error", error: error});
}
else{
response.json({message: "success!", data: newfigure});
}
});
}})
预期结果是看到具有以下结果的对象(对不起,我正在测试它的愚蠢日期):
{
"_id" : ObjectId("5c319fdb41c91e0663c2d008"),
"currencytype" : "JPY",
"pictures" :[
"images/pictures/43958469.2_4589642701118_primary.jpg",
"images/pictures/1543613133070.jpg","images/pictures/1545875011468.jpg"],
"name" : "1212121",
"releasedate" : ISODate("2019-12-12T00:00:00.000Z"),
"announcedate" : ISODate("2018-12-12T00:00:00.000Z"),
"brand" : "adfasdf",
"series" : "asdfasd",
"number" : 1212121212,
"manufacturer" : "waefasdf",
"distributor" : "efsdfsdf1",
"releaseprice" : 1000,
"notes" : "sdfasdfasdfsadf",
"createdAt" : ISODate("2019-01-06T06:27:39.703Z"),
"updatedAt" : ISODate("2019-01-06T06:27:39.703Z"),
"__v" : 0
}
但是,当POST路径被命中时,它不保存而是命中response.json({message:“ Error”,error:error});图像确实保存到了预期的区域,但是文件路径和整个mongo对象没有保存,从而发送错误。
感谢您阅读。