在我的资料图片模型中创建了两个表user和employee的引用。我使用的是monogo db。我想要显示用户/员工上传的个人资料图片。图片上传成功,但未显示。当我重定向到页面时,它显示错误。
Cannot read property 'profileImg' of undefinedroute.js中未出现profileImg错误。它在我想要在屏幕上显示最新上传图片的ejs文件中显示profileImg错误
profilePicModel.js
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 = profileroute.js
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 = routerprofile.ejs
<!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>发布于 2021-07-01 20:58:58
您可能希望从构造函数创建一个新对象
const profileImgModel = require('../../models/profileImgModel')
const profilePic = new profileImgModel()然后更新该条目
const filter = { userId: user };
const update = { profileImg: req.file.filename }
let doc = await profilePic.findOneAndUpdate(filter, update)https://stackoverflow.com/questions/68210457
复制相似问题