首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用express.js显示登录用户资料图片

如何使用express.js显示登录用户资料图片
EN

Stack Overflow用户
提问于 2021-07-01 20:45:18
回答 2查看 53关注 0票数 0

在我的资料图片模型中创建了两个表user和employee的引用。我使用的是monogo db。我想要显示用户/员工上传的个人资料图片。图片上传成功,但未显示。当我重定向到页面时,它显示错误。

代码语言:javascript
复制
     Cannot read property 'profileImg' of undefined

route.js中未出现profileImg错误。它在我想要在屏幕上显示最新上传图片的ejs文件中显示profileImg错误

profilePicModel.js

代码语言:javascript
复制
const mongoose = require('mongoose')
const Users = require("./authUserModel");
const Employee = require("./employeeModel");
const Schema  = mongoose.Schema
const profilePic = new Schema({
    userId:{
       type:mongoose.Schema.Types.ObjectId ,
       ref:Users || Employee,
    },

    profileImg:{
       type: String
    }
})
profile = mongoose.model('Profile', profilePic)
module.exports = profile

route.js

代码语言:javascript
复制
const express = require('express')
const router = express.Router()
const multer = require('multer')
const path = require('path')
const profilePic = require('../../models/profileImgModel')

function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
    req.isLogged = true
    return next();
}
else{
    req.isLogged = false
    return next()
}
}

router.get('/profilePic', isLoggedIn ,((req, res) => {
     res.render('profilePic', {user:req.user , isLoggedIn: req.isLogged}) 
}))

router.post('/profilePic',upload,  function (req, res, next){
    let user = req.user
    let pic = profilePic({
        userId: user,
        profileImg: req.file.filename
    })
    pic.save()
      .then((result)=>console.log(result))
      .catch(err=>console.log(err))
    res.redirect('/customerMenu', 200)
})

module.exports = router

profile.ejs

代码语言:javascript
复制
<!Doctype Html>
<html lang="en">

<head>
   <title>Upload pic</title>
</head>
<body>
<% if( isLoggedIn){%>
   <img src="./public/uploads/<%= isLoggedIn.user.profileImg  %>" alt="profile pic">
<%}%>
<form method="post" enctype="multipart/form-data" action="/profilePic">

     <label>Upload Pic</label>
     <input type="file" name="file">
     <button type="submit">upload</button>
</form>
</body>
</html>
EN

Stack Overflow用户

发布于 2021-07-01 20:58:58

您可能希望从构造函数创建一个新对象

代码语言:javascript
复制
const profileImgModel = require('../../models/profileImgModel')   
const profilePic = new profileImgModel()

然后更新该条目

代码语言:javascript
复制
const filter = { userId: user };
const update = { profileImg: req.file.filename }
let doc = await profilePic.findOneAndUpdate(filter, update)
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68210457

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档