TypeError:无法读取未定义的属性“位置” &&无法读取属性' location'不确定的

时间:2020-01-05 13:37:43

标签: javascript node.js mongodb amazon-web-services

曾经尝试使用AWS S3(Multer和MulterS3)发布带有图像的产品。每次我使用邮递员时,都会收到“ TypeError:无法读取未定义的属性'location'”,这是我拥有Image变量的那一行。我做错了什么? 这是我的代码。

seller.js

const express = require('express');
const router = express.Router();
const Product = require('../models/product');
const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');
const s3 = new aws.S3({accessKeyId:"XXXXX",secretAccessKey:"XXXXXX"})

const checkJWT = require('../middlewares/check-jwt');

/* image filter */
const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, true)
    } else {
        cb(new Error('Invalid Mime Type, only JPEG and PNG'), false);
    }
  }

const upload = multer({
    fileFilter,
    storage: multerS3({
      s3: s3,
      bucket:'XXXXX',
      metadata: function (req, file, cb) {
        cb(null, {fieldName: file.fieldname});
      },
      key: function (req, file, cb) {
        cb(null, Date.now().toString())
      }
    })
  })

router.route('/products')
   .post([checkJWT, upload.single('product_picture')], (req, res, next) => {
   let product = new Product();
   product.owner = req.decoded.user._id;
   product.category = req.body.categoryId;
   product.title = req.body.title;
   product.price = req.body.price;
   product.description = req.body.description;
   product.image = req.file.location;
   product.save();
   res.json({
       success: true,
       message: 'Successfully Added the product'
   });
})
module.exports = router;

product.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    category: { type: Schema.Types.ObjectId, ref: 'Category' },
    owner: { type: Schema.Types.ObjectId, ref: 'User' },
    reviews: [{ type: Schema.Types.ObjectId, ref: 'Review' } ],
    image: String,
    title: String,
    description: String,
    price: Number,
    created: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Product', ProductSchema);

为什么我不将图像存储在s3中。请帮助我。

0 个答案:

没有答案