简体   繁体   English

如何使用 ejs 发布表单更新 node.js 和 MongoDB 应用程序中的现有用户数据?

[英]How to update existing user data in a node.js and MongoDB app with ejs post form?

I am extremely new to javascript and found Brad Traversy's video Node.js with Passport Authentication and followed his video to a t.我对 javascript 非常陌生,发现 Brad Traversy 的视频 Node.js 带有 Passport Authentication 并关注他的视频。

It worked for me, but then I wanted to add more.它对我有用,但后来我想添加更多。 I created a custom dashboard and navigation.我创建了一个自定义仪表板和导航。 One page I added was a user profile page.我添加的一个页面是用户个人资料页面。 I added this because I want to be able to update the user's information if possible.我添加这个是因为我希望能够尽可能更新用户的信息。

Now I'm stuck.现在我卡住了。 I think I'm having an issue with my.findOneAndUpdate function that I placed in my route index.js.我认为我在我的路线 index.js 中放置的 my.findOneAndUpdate function 有问题。 I may not be using the funcion correctly.我可能没有正确使用该功能。 I am currently console logging req.body.name as well as req.user.name.我目前正在控制台记录 req.body.name 以及 req.user.name。

req.body.name is what the user is inputting as the new name, req.user.name is the original name. req.body.name 是用户输入的新名称,req.user.name 是原始名称。

top and bottom of index.js index.js 的顶部和底部

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

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

function updateRecord(req, res) {
User.findOneAndUpdate({ "_id": req.body._id },{
    $set: {
        "name": req.body.name
    }
 }, { new: true }, (err, doc) => {
    if (!err) { 

        console.log(req.user.name);
        console.log(req.body.name);
        res.redirect('/profile'); 
    }
    else {
        console.log('Error during record update : ' + err);
    }
 });
}



module.exports = router;

edit.ejs编辑.ejs

<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>

User.js用户.js

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});

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

module.exports = User;

EDIT编辑

I followed THEWOLF's instructions and it is now updating to the database, However, now when I click my 'Save Changes' button.我按照 THEWOLF 的说明进行操作,它现在正在更新到数据库,但是,现在当我单击“保存更改”按钮时。 it redirects to the profile page but displays the old name.它重定向到个人资料页面但显示旧名称。 Only when you refresh the page or navigate away from it does the updated name show on my website.只有当您刷新页面或离开页面时,更新后的名称才会显示在我的网站上。

Here is new index.js code这是新的 index.js 代码

router.post('/', (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){

});

 });

in your requiring User model do it like this 在您需要的用户模型中这样做

const User=require('../models/User');

then 然后

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

// then save that document
doc.save(callback);

});

}
 await UserSchema.findByIdAndUpdate({ _id: _id }, { name:req.body.name }, (err, updated) => {
    if (!err) {
         return res.status(201).send({
            status: true,
            message: "User Account Updated Successfully!",
         });
    }
    else{
        return res.status(500).send({
            status: false,
            error: err.message,
         });
    }
}).clone();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM