res.redirect在提交表单后显示旧信息?

res.redirect在提交表单后显示旧信息?

问题描述:

我有一个node.js应用程序,其中创建了一个用户个人资料页面.我将其设置为可编辑,以便他们可以根据需要更新其名称.

I have a node.js app in which I created a user profile page. I made it editable so they can update their name if they want to.

但是,当我单击表单上的保存更改"按钮时,它会重定向到正确的页面,但显示旧信息.只有刷新页面或离开页面后,才会显示更新的信息.

However, when I click the 'Save Changes' button on the form, it redirects to the correct page but shows the old information. Only once you refresh the page or navigate away from it does the updated information show.

提交表格html:

<form action="./profile" method="POST">
<div class="form-group">
    <label for="">Full Name</label>
    <input type="text" class="form-control" value="<%= name %>" 
name="name"> 
</div>
<div class="form-group" >
    <label for="">email</label>
    <input type="text" class="form-control" value="<%= email %>" readonly>
</div>
<div class="form-row">
    <div class="form-group">
        <button type="submit" class="btn btn-info"><a href="profileEditor"> 
</a> Save Changes</button>
    </div>
    <p>&nbsp; &nbsp;</p>
    <div class="form-group">
        <button class="btn btn-dismiss"><a href="./profile">Exit</a> 
</button></a>
    </div>
</div>

</form>

index.js的一部分(在我的路由文件夹中)

parts of index.js (in my routes folder)

const express = require('express');
const router = express.Router();
const { ensureAuthenticated } = require('../config/auth');
const mongoose = require('mongoose');
const User = require('../models/User');

router.post('/', ensureAuthenticated, (req, res) => {
   updateRecord(req,res);
   res.redirect('/profile');
});

function updateRecord(req, res) {
User.findOne({_id:req.user.id},(err,doc)=>{
 //this will give you the document what you want to update.. then 
doc.name = req.body.name;
doc.save(function(err,doc){
}); 
});   
}

module.exports = router;

在我的router.post函数下,res.redirect可以工作并将用户发送到"/profile",但不显示更新的数据库信息.请帮忙!

under my router.post function, the res.redirect works and sends the user to '/profile' but doesn't show the updated database info. Please help!

您可以直接使用findOneAndUpdate()函数更新用户配置文件.尝试如下操作:

You can directly use findOneAndUpdate() function to update user profile. Try as below:

const express = require('express');
const router = express.Router();
const { ensureAuthenticated } = require('../config/auth');
const mongoose = require('mongoose');
const User = require('../models/User');

router.post('/', ensureAuthenticated, (req, res) => {
  User.findOneAndUpdate({_id:req.user.id},{name: req.body.name},{new: true},(err,doc)=>{
       console.log('#### Updated Record ####',doc);
       res.redirect('/profile');
  });   
});



module.exports = router;