簡體   English   中英

如何從 MERN 客戶端更新 MongoDB 記錄

[英]How do I update MongoDB records from client side in MERN

我正在嘗試實現代碼,讓用戶通過更新 mongoDB Atlas 中的 URL 來更改他們的個人資料圖片。 用戶在表單中輸入 URL,然后按下它旁邊的按鈕。 這是應該通過按下按鈕到達的路線的代碼:

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

當我在這里輸入一個特定的 URL ( 'https://i.imgur.com/Geb0OcA.png' ) 時,它會正確更新,但我似乎無法弄清楚我需要用什么來替換硬編碼的 URL在客戶端任意獲取用戶在表單中輸入的信息。

下面是 server.js 中的相關路由代碼:

const changeProfilePicRouter = require("./routes/changeProfilePic");
app.use("/api/changeProfilePic", changeProfilePicRouter);

這是用戶架構:

用戶模型.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;

這是一個帶有 axios 函數的組件,用於在按下按鈕時轉到 changeProfilePic 路由:

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;

我正在使用 Passport.js 進行授權

抱歉,如果我遺漏了任何相關代碼或信息! 我不是想對我的問題偷懶,我只是不知道要展示什么是重要的。 如果需要,我可以快速編輯和添加更多內容。

我已經檢查了與我的(我能找到的)類似的其他問題的解決方案,到目前為止,它們都沒有幫助。

在 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

第 1 行和第 5-6 行是假設您使用 express 4.x 的一些配置(否則,您應該安裝 body-parser,並在需要之后將 express 更改為 body-parser)。

第 9 行使用 req.body。 http://expressjs.com/en/4x/api.html#req.body閱讀更多相關信息

編輯:如果你還沒有,你還應該在最后有類似res.status(200).send()東西來發送響應

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM