[英]How do I update MongoDB records from client side in MERN
I am trying to implement code to let users change their profile pic via updating a URL in mongoDB Atlas.我正在尝试实现代码,让用户通过更新 mongoDB Atlas 中的 URL 来更改他们的个人资料图片。 The user enters the URL into a form then presses a button next to it.用户在表单中输入 URL,然后按下它旁边的按钮。 here is the code for the route that should be reached on the press of a button:这是应该通过按下按钮到达的路线的代码:
changeProfilePic.js更改ProfilePic.js
const router = require("express").Router();
const User = require("../models/user.model");
router.put('/', (req, res, next) => {
const id = req.user.id
const query = {$set:{image: 'https://i.imgur.com/Geb0OcA.png'}}
User.findByIdAndUpdate(id, query, {new: true, useFindAndModify: false})
.then()
});
module.exports = router
When I put in a specific URL here ( 'https://i.imgur.com/Geb0OcA.png'
), it updates correctly, but I can't seem to figure out what I need to replace the hard coded URL with to get the informtion the user typed in the form on the client side arbitrarily.当我在这里输入一个特定的 URL ( 'https://i.imgur.com/Geb0OcA.png'
) 时,它会正确更新,但我似乎无法弄清楚我需要用什么来替换硬编码的 URL在客户端任意获取用户在表单中输入的信息。
Here is the relevant routing code in server.js:下面是 server.js 中的相关路由代码:
const changeProfilePicRouter = require("./routes/changeProfilePic");
app.use("/api/changeProfilePic", changeProfilePicRouter);
here is the user schema:这是用户架构:
user.model.js用户模型.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
googleId: {
type: String,
},
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3,
},
password: {
type: String,
trim: true,
},
email: String,
image: {type: String, default: 'https://i.imgur.com/Geb0OcA.png'},
date: {type: Date, default: Date.now},
tps: {type: Number, default: 0},
},
);
const User = mongoose.model("User", userSchema);
module.exports = User;
Here is a component with an axios function to go to the changeProfilePic route on button press:这是一个带有 axios 函数的组件,用于在按下按钮时转到 changeProfilePic 路由:
changeProfilePic.component.js changeProfilePic.component.js
import React, { useState } from "react";
import Axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
import { Button, Form, Col } from "react-bootstrap";
function HookChangeProfilePic() {
const [profilePicSrc, setProfilePicSrc] = useState("");
const changeProfilePic = () => {
Axios({
method: "PUT",
data: {
image: profilePicSrc
},
withCredentials: true,
url: "/api/changeProfilePic",
}).then((window.location.href = "/profile")).catch((err) => console.log(err));
};
return (
<div>
<Form className="m-0">
<Form.Row className="justify-content-md-center m-4">
<Col xs="auto">
<Form.Control
onChange={(e) => setProfilePicSrc(e.target.value)}
type="text"
placeholder="Enter Image Src"
/>
</Col>
<Button variant="warning" onClick={changeProfilePic}>
Update Profile Picture
</Button>
</Form.Row>
</Form>
</div>
);
}
export default HookChangeProfilePic;
I am using Passport.js for authorization我正在使用 Passport.js 进行授权
sorry if i am missing any relevant code or informtion!抱歉,如果我遗漏了任何相关代码或信息! I'm not trying to be lazy with my question, I just don't know what is important to show.我不是想对我的问题偷懒,我只是不知道要展示什么是重要的。 I can quickly edit and add more stuff if needed.如果需要,我可以快速编辑和添加更多内容。
I have checked the solutions to other questions that were similar to mine (that I could find) and none of them have helped so far.我已经检查了与我的(我能找到的)类似的其他问题的解决方案,到目前为止,它们都没有帮助。
In changeProfilePic.js, you should add/change the following code:在 changeProfilePic.js 中,您应该添加/更改以下代码:
const express = require('express')
const router = express.Router();
const User = require("../models/user.model");
router.use(express.json());
router.use(express.urlencoded({extended: true}))
router.put('/', (req, res, next) => {
const id = req.user.id
const update = {$set:{image: req.body.image}}
User.findByIdAndUpdate(id, query, {new: true, useFindAndModify: false})
.then()
});
module.exports = router
Lines 1 and 5-6 are some config assuming you are using express 4.x (otherwise, you should install body-parser, and change express to body-parser after requiring it).第 1 行和第 5-6 行是假设您使用 express 4.x 的一些配置(否则,您应该安装 body-parser,并在需要之后将 express 更改为 body-parser)。
Line 9 uses req.body.第 9 行使用 req.body。 Read more about it at http://expressjs.com/en/4x/api.html#req.body在http://expressjs.com/en/4x/api.html#req.body阅读更多相关信息
Edit: If you don't already, you should also have something like res.status(200).send()
at the end to send the response back编辑:如果你还没有,你还应该在最后有类似res.status(200).send()
东西来发送响应
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.