使用 multer 将图像上传到 API

Uploading an image to an API with multer

我正在尝试制作一个需要图像上传和存储的应用程序,我正在使用 Express、Mongoose 和 Multer 并尝试上传到 MongoDB。

目前,当我尝试上传图像时,Multer 会创建一个文件夹并将图像存储在该文件夹中,但它不会将项目保存到数据库中,并且会导致服务器崩溃并给出错误:ObjectParameterError: Parameter "obj" to Document() must be an object, got itemImages4ed9d34a3b034becdb415d67b7d193.

添加到数据库工作正常,无需尝试使用 multer 添加图像。

我的代码:

item_controller.js:

const Item = require('../models/item_schema');

const addItem = (req, res) => {
    let itemData = req.body
    let itemImage = req.file.path

    Item.create(itemData, itemImage)
        .then((data) => {
            if (data) {
                res.status(201).json(data)
            }
        })
}

module.exports = {
    addItem
}

item_schema.js

const { Schema, model} = require('mongoose')

const itemSchema = new Schema({
    title: {
        type: String,
        required: [true, 'Title field is required.']
    },
    description: {
        type: String,
        required: [true, 'Description field is required.']
    },
    itemImage: {
        type: String,
        required: [true, 'Image field is required.']
    },
    userID: {
        type: Schema.Types.ObjectId,
        ref: "User",
        required: [true, 'User field is required']
    },
    categoryID: {
        type: Schema.Types.ObjectId,
        ref: "Category",
        required: [true, 'Category field is required']
    },
    qualityID: {
        type: Schema.Types.ObjectId,
        ref: "Quality",
        required: [true, 'Quality field is required']
    },
    price: {
        type: Number
    },
    claimed:{
        type: Boolean
    }
}, {
    timestamps: true
})

module.exports = model('Item', itemSchema)

server.js:

const express = require('express')
const cors = require('cors')
const jwt = require('jsonwebtoken')
const multer = require('multer');
const upload = multer({dest: 'itemImages/'});

require('dotenv').config()
require('./db')()

const { addItem } = require('./controllers/item_controller')
const { loginRequired } = require('./controllers/user_controller')

const app = express()
app.use(cors())
app.use(express.json())

app.post('/items', upload.single('itemImage'), loginRequired, addItem)

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

在你的 item_controller.js 中试试这个:

const addItem =  (req, res) => {
 let itemData = req.body
 let itemImage = req.file.path

 Item.create({
  title: itemData.title,
  description: description ,
  itemImage: itemImage ,
  userID: item.userID ,
  categoryID: item.categoryID ,
  qualityID: item.qualityID,
  //put all data that are required here...
 }, (err,, data)=> {
  if (err) return handleError(err) //here you custom handleError of Just res.status(400).json(err);

  res.status(201).json(data)
 })
}

Model.create 接收第一个参数 属性 你想保存在模型中的所有参数,第二个参数是一个闭包。