Как загрузить изображение в mongodb, используя node.js, express. js - PullRequest
0 голосов
/ 20 июня 2020

Я пытаюсь загрузить изображение в коллекцию задач в моем mongodb, но продолжаю получать сообщение об ошибке.

вот моя модель задачи

const mongoose = require('mongoose')


const taskSchema = new mongoose.Schema({
    description: {
        type: String,
        trim: true,
        required: true
    },
    completed: {
        type: Boolean,
        default: false
    },
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    }, 
    avatar: {
        type: Buffer
    }
},
    {
    timestamps: true
})

const Tasks = mongoose.model('Tasks', taskSchema )


module.exports = Tasks

Вот мой код маршрутизатора задачи

router.post('/tasks/me/avatar', auth, upload.single('avatar'), async (req, res) => {
    const buffer = await sharp(req.file.buffer).resize({ width: 250, height: 250 }).png().toBuffer()
    req.tasks.avatar = buffer
    await req.tasks.save()
    res.send()
}, (error, req, res, next) => {
    res.status(400).send({ error: error.message })
})

сообщение об ошибке

[![enter image description here][1]][1]

Он продолжает давать мне сообщение об ошибке «Невозможно установить для свойства« аватар »значение undefined, при этом поле аватара уже было определено в модели задачи.

Как я могу исправить эту проблему, спасибо.

1 Ответ

0 голосов
/ 20 июня 2020

Хорошо, посмотрев ваш ответ, я предложу это решение.

Вместо:

req.tasks.avatar = buffer
await req.tasks.save()

Попробуйте это

 const query = {id: docId}; //prepare a query to find the doc
 Task.findOneAndUpdate(query, { $set: {avatar: buffer} }, ()=>{
   /Your callback function to run after completed
 });
 //Then call findOneAndUpdate method from any mongoose.model
 //Which will do exactly what its name says:
 //Finding ONE element, the first one matching your query
 //And then update any values inside $set
 //And after that you may use any callback function

Сообщите мне, если это выручает.

...