【问题标题】:Cannot update db with multer and mongose无法使用 multer 和 mongoose 更新数据库
【发布时间】:2021-08-30 14:57:29
【问题描述】:

我正在使用 mongoose 和 node.js 来查找文档并更新其属性,但每次我这样做时都会出现某种错误,无法登录控制台。这是 multer 的一些问题。谁能猜出 id 做错了什么?

我的架构:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name : {
        type: String,
        required: true
    },
    email : {
        type: String,
        required: true
    },
    password : {
        type: String,
        required: true
    },
    details: {
    type: Object,
},
profile_img: {
    data: String,
    contentType: String,
}
})

const User = mongoose.model('User',UserSchema);

module.exports = User

Multer 码:

var fs = require('fs');
var path = require('path');

var multer = require('multer');
 

//store images in db 
var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads')
    },
    filename: (req, file, cb) => {
         cb(null, new Date().toISOString().replace(/:/g, '-')+ file.originalname);
    }
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter
});

路线:

router.post('/profile-chooser/developer/:method',upload.single('profile_photo'),ensureAuthenticated,(req,res) => {
  
        //do db stuff
        User.findOneAndUpdate({ "_id": mongoose.Types.ObjectId(req.user._id) },
         { "$set": 
            { 
                "details": {
                    "Some stuff": "update itttt"
                },
                "profile_img": {
                    "data": fs.readFileSync(path.resolve(__dirname, '../uploads/' + req.file.filename)),
                    "contentType": 'image/png'
                }
            }
        })
        .exec(function(err, user){
            if(err) {
                console.log(err);
                res.status(500).send(err);
            } else {
                res.status(200).send(user);
            }
        });
    })  

我确信这是 multer 的一个问题,因为当我将 fs.readFileSync(path.resolve(__dirname, ../uploads/ + req.file.filename)) 这行更改为字符串并删除了 upload.single(profile_photo) 时,它神奇地起作用了。

谁能帮帮我。

我们将非常感谢您的快速响应。

提前致谢。

【问题讨论】:

  • 您如何在 mongodb 中检查您的收藏?
  • _id: req.user._id - 如果 _id 是自动生成的,它将是 ObjectId,而 req.user._id 几乎可以肯定是 String。见stackoverflow.com/a/55874520/2282634
  • @tbking 我正在通过 mongodb ui 进行检查
  • @Joe 我已经做到了,当我转到我的 mongodb ui 中的用户集合时,我仍然看到错误 - There was a problem retrieving data from this collection. Check your query and try again. 我认为这是我的架构结构的问题,我怎么样迭代它
  • 如果您认为这可能是 multer 问题(我不知道是否是这种情况),您可以尝试暂时注释掉与 multer + recreate database 相关的代码。

标签: node.js mongoose multer multer-gridfs-storage


【解决方案1】:

我想通了。使用 multer 与 multer-gridfs-storage 和 grid-fs-stream 将照片读/写到数据库中。

创建一个中间件文件夹并添加以下代码行:

const multer = require("multer");
const {GridFsStorage} = require("multer-gridfs-storage");

const storage = new GridFsStorage({
    url: process.env.CONNECTION_URL,
    options: { useNewUrlParser: true, useUnifiedTopology: true },
    file: (req, file) => {
        const match = ["image/png", "image/jpeg"];

        if (match.indexOf(file.mimetype) === -1) {
            const filename = `${Date.now()}-any-name-${file.originalname}`;
            return filename;
        }

        return {
            bucketName: "photos",
            filename: `${Date.now()}-any-name-${file.originalname}`,
        };
    },
});

module.exports = multer({ storage });

无论您在何处发布数据。

在需要后添加这个中间件:

upload.single('profile_photo')

Grid fs 流允许我们读取/写入集合。

如果你想给你的收藏起个名字:

let gfs;

const conn = mongoose.connection;
conn.once("open", function () {
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection("photos");
});

是的,就是这样。你已经成功学会写字母了!

外部链接(如果你是认真的请按顺序参考这些链接)。

Complete reference for beginners

高级用法:

Multer docs(well written)

Grid-fs-storage(the core of our project)

Grid-fs-stream

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2019-05-17
    • 2016-06-16
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多