Home > Net >  MongoDB update user
MongoDB update user

Time:12-11

I'm trying to update user, but it gives me this error: enter image description here

I can't find any solution of it. Tried to use different UserSchema methods, like findOneAndUpdate, updateOne, but nothing helps..

This is my mainController:

 updateUser: async (req, res) => {
        try {
            const updatedUser = await UserSchema.updateOne({ secret: req.params.secret }, { $set: req.body });
            res.status(200).json(updatedUser);
        } catch (error) {
            res.status(400).json({ message: error.message });
        }
    },

This is my router:

mainRouter.post('/update/:secret', updateUser)

This is where I'm posting in front end:

import React, { useState, useEffect } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import Toolbar from '../components/Toolbar';
import { get, post } from '../helper/helper';

export default function TestPage() {

    const [current, setCurrent] = useState('')
    const [index, setIndex] = useState(0);
    const [allUsers, getAllUsers] = useState([])
    const secret = window.localStorage.getItem('secret')
    const nav = useNavigate()

    useEffect(() => {
        async function currentUser() {
            const resp = get(`user/${secret}`)
            setCurrent(resp)
        }
        currentUser()
    }, [])

    useEffect(() => {
        async function fetchUsers() {
            const resp = await get('api')
            getAllUsers(resp)
        }
        fetchUsers()
    }, [])

    allUsers.filter(user => user.secret !== secret)
    console.log(index)
    const currentUser = allUsers[index];

    async function postLiked() {
        const likedObj = {
            liked: [currentUser]
        }
        const likesObj = {
            likes: [current]
        }
        await post(`update/${current.secret}`, likedObj)
        await post(`update/${currentUser.secret}`, likesObj)
    }

    async function postDislike() {
        const dislikeObj = {
            disliked: [currentUser]
        }
        await post(`update/${current.secret}`, dislikeObj)
    }


    return (
        <div className='home__page'>
            <Toolbar />
            <div className="home__users">
                <div className='single__user'>
                    <img src={currentUser && currentUser.image[0]} alt="" />
                    <h3>{currentUser && `${currentUser.firstName} ${currentUser.lastName}`}</h3>
                    <h4>{currentUser && currentUser.gender}</h4>
                    <button onClick={() => { setIndex(index   1); postDislike(); nav(`/${currentUser.secret}`) }}>Dislike</button>
                    <button onClick={() => { setIndex(index   1); postLiked(); nav(`/${currentUser.secret}`) }}>Like</button>
                </div>
            </div>
            <footer className='footer'>
                <p>All rights reserved by Cartoon Match organization. To read more about our policy <Link to='/policy'>click here</Link>. </p>
            </footer>
        </div>
    )
}

helper.js:

export const get = async (url) => {
    const options = {
        method: 'GET',
        headers: {
            'Content-type': 'application/json',
        },
    };
    const response = await fetch(`http://localhost:4000/${url}`, options);
    if (response.ok) {
        const dataFromGetRequest = await response.json();
        return dataFromGetRequest;
    }
};

export const post = async (body, url) => {
    const options = {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
        },
        body: JSON.stringify(body),
    };
    const response = await fetch(`http://localhost:4000/${url}`, options);
    if (response.ok) {
        const dataFromPostRequest = await response.json();
        return dataFromPostRequest;
    }
};

export const put = async (body, url) => {
    const options = {
        method: 'PUT',
        headers: {
            'Content-type': 'application/json',
        },
        body: JSON.stringify(body),
    };
    const response = await fetch(`http://localhost:4000/${url}`, options);
    if (response.ok) {
        const dataFromPostRequest = await response.json();
        return dataFromPostRequest;
    }
};

CodePudding user response:

If react and node.js run on different port, Browser refuse to connect.

Add this line after const app = express();

app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS, GET,  PUT, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization,token-type");
next();
});
  • Related