繁体   English   中英

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

[英]How to upload image to mongodb using node.js, express.js

我正在尝试将图像上传到我的 mongodb 中的任务集合,但不断收到错误消息。

这是我的任务 model

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]

它一直给我一个错误消息,无法设置未定义的属性“头像”,同时头像字段已经在任务 model 中定义。

我该如何解决这个问题,谢谢。

好的,在查看您的答案后,我会提出这个解决方案。

代替:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM