【问题标题】:How to put image into mongodb using node js如何使用节点 js 将图像放入 mongodb
【发布时间】:2020-01-28 20:24:13
【问题描述】:

我想将个人资料图片放入 mongodb 中的用户集合中,并且我想在用户获取他的个人资料时检索此图片。

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/')
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname));
    }
});
var upload = multer({ storage: storage });
router.put('/user/profile/img/:email', upload.single('profileimg'), (req, res, next) => {
    // console.log(req.file);
    Users.findOneAndUpdate({ email: req.params.email }, req.file.filename).then(() => {
        Users.findOne({ email: req.params.email }).then((resp, err) => {
            res.send(resp);
        })
    })
})

图像被保存在我的 api 的上传文件夹中,但它没有保存在 db 中。

【问题讨论】:

标签: node.js mongodb express multer


【解决方案1】:

findOneAndUpdate函数的第二个参数必须是一个包含要更新的字段和值的对象:

Users.findOneAndUpdate({ email: req.params.email }, { profileimg: req.file.filename }).then(...)

【讨论】:

  • 函数调用的结果是什么?
  • 以空 profileimg 字段作为用户 json 获得响应。
  • 是的,您需要在第二个参数中输入正确的字段名称。我已经编辑了。
  • 那么我们需要更多详细信息,您的代码中的其他地方可能存在错误。
【解决方案2】:

你可以像下面的代码那样做:

router.put('/user/profile/img/:email', upload.single('profileimg'), async (req, res, next) => {
  try {
    // check your file is uploaded
    // check your field
    console.log(req.file);
    const result = await Users.findOneAndUpdate({ email: req.params.email }, {$set: { profileimage : req.file.filename}}, { returnOriginal: false})
    res.send(result)
  } catch(ex) {
    res.status(500).send(ex.message);
  }
})

注意:为此{$set: { profileimage : req.file.filename}}

  • profileimage :随 mongodb 中的字段变化
  • req.file.filename:确保console.log(req.file) 然后,你要存储的字段,在这里使用它并更改此示例。

希望对你有帮助。

【讨论】:

  • 将名称更改为 profileimage 但仍然无法使用
  • 当你console.log(req.file)时,你得到了什么对象?
  • { 字段名:'profileimg',原始名称:'1.png',编码:'7bit',mimetype:'image/png',目的地:'uploads/',文件名:'profileimg-1580208697681 .png',路径:'uploads\\profileimg-1580208697681.png',大小:3368 }
  • 我已经在我的答案中更新了我的代码。你可以试试。我希望你复制上面的代码并替换你的
  • $set 是不必要的,因为猫鼬会在内部处理它。
猜你喜欢
  • 2023-02-08
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 2020-12-16
  • 2020-08-08
  • 2019-01-23
  • 2021-07-17
相关资源
最近更新 更多