【发布时间】:2019-04-26 21:13:50
【问题描述】:
我正在尝试上传一张带有“价格”等额外字段的小图片。 img 似乎存储在 destination 文件夹中,但额外的字段未与文件一起保存。
我正在使用 multer 和 bodyParser.json 来读取 req.body 和 req.file 的字段。
这是帖子:
router.route('/pictures/add').post(upload, (req, res) => {
console.log(req.body.price); //works
console.log(req.file); //works
var picture = new Picture({
name : req.file.originalname,
price : req.body.price,
id : req.file.filename
});
console.log(picture); //logs only the id as in req.file.filename.
//name and price are missing
picture
.save()
.then(picture => {
console.log(picture);
res.status(201).json({
picture: 'Added successfully',
id: picture.id, //id as in req.file.filename
name: picture.name, //missing
price: picture.price //missing
});
})
这是 multer 实例
const upload = multer({dest: 'pictures/'}).single('img');
app.use(bodyParser.json());
这是图片架构
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
let Picture = new Schema({
name: {
Type: String
},
price: {
Type: String
}
});
export default mongoose.model('Picture', Picture);
我希望数据库能像这样保存所有字段:id、name、price 但似乎只有 id 被发送并保存到数据库中。
我欢迎任何帮助。
【问题讨论】:
-
显示 req.body.price 和 req.file
标签: javascript node.js mongodb express