【问题标题】:How do I update MongoDB records from client side in MERN如何在 MERN 中从客户端更新 MongoDB 记录
【发布时间】:2021-02-02 18:18:05
【问题描述】:

我正在尝试实现代码,让用户通过更新 mongoDB Atlas 中的 URL 来更改他们的个人资料图片。用户将 URL 输入到表单中,然后按下它旁边的按钮。这是按下按钮应到达的路线的代码:

changeProfilePic.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);

这是用户架构:

user.model.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 进行授权

抱歉,如果我遗漏了任何相关代码或信息!我并不是想对我的问题偷懒,我只是不知道要展示什么重要。如果需要,我可以快速编辑和添加更多内容。

我已经检查了与我类似的其他问题的解决方案(我能找到),但到目前为止没有一个有帮助。

【问题讨论】:

    标签: node.js express mongoose axios mern


    【解决方案1】:

    在 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() 之类的东西来发回响应

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多