如何使用node.js,express.js将图像上传到mongodb

时间:2020-06-20 02:09:28

标签: node.js mongodb express

我正在尝试将图像上传到我的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]

它一直给我一个错误消息,提示无法将属性'avatar'设置为undefined,同时在任务模型中已经定义了avatar字段。

如何解决此问题,谢谢。

1 个答案:

答案 0 :(得分:0)

确定您的答案后,我将提出此解决方案。

代替:

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

让我知道这是否对您有帮助。