我正在使用 MERN 堆栈构建一个简单的 CRUD 应用程序 下面是在db中添加用户详细信息的代码
import React , {useState, useEffect} from 'react' import axios from 'axios'; import { useNavigate } from 'react-router-dom'; const initialValue = { name: '', username: '', email: '', phone: '' } const AddUser = () => { // hooks const [user, setUser] = useState(initialValue); const { name, username, email, phone } = user; let navigate = useNavigate(); const onValueChange = (e) => { setUser({...user, [e.target.name]: e.target.value}) } // ADD USER const config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } const addUser = async (user) => { return await axios.post("http://localhost:5000/add", user , config); } const addUserDetails = async() => { await addUser(user); navigate('/all'); } return ( <div> <h1>Add Details</h1> <form className="form"> <input onChange={(e) => onValueChange(e)} placeholer="Add Name"name='name' value={name} id="my-input" /> <input onChange={(e) => onValueChange(e)} placeholer="Add Username"name='username' value={username} id="my-input" /> <input onChange={(e) => onValueChange(e)} placeholer="Add Email"name='email' value={email} id="my-input" /> <input onChange={(e) => onValueChange(e)} placeholer="Add Phone"name='phone' value={phone} id="my-input" /> <button type="submit" onClick={() => addUserDetails()}>Add</button> </form> </div> ) } export default AddUser
下面是mongodb的截图
下面是Route.js
const router = require('express').Router(); const User = require('../model/todoItems.js'); // Coming from model // POST DATA router.post('/add',async (req,res) =>{ try { const newUser = new User({user: req.body.user}); // saving in db await newUser.save(); res.status(201).json(newUser); } catch (error) { res.status(409).json({ message: error.message}); } } ); module.exports = router;
下面是模型
const mongoose = require( 'mongoose'); const userSchema = new mongoose.Schema({ user:{ name: String, username: String, email: String, phone: Number } }); module.exports= mongoose.model('user', userSchema);
{_id:ObjectId(641548f49338e07c498bf231),__v:0} 这就是我得到的 数据库连接成功。 我希望发布所有详细信息,我该怎么办?
P粉1788942352024-02-22 16:50:51
您的代码中有一些错误。我想当你纠正它们时问题就会解决。
1-) 检查您在route.js 中导入了正确的模型。因为它是todoItem.js。我想这一定是和用户有关的。
const User = require('../model/todoItems.js');
2-) 在 mongoose 模型中,不需要使用 user 作为父级。只需将其删除,使其看起来像:
const userSchema = new mongoose.Schema({ name: String, username: String, email: String, phone: Number });
3-) 在route.js 中,更改 const newUser 行,如下所示:
const newUser = new User(req.body);
4-) 确保使用 console.log 获得正确的 req.body
console.log("req.body: ", req.body); const newUser = new User(req.body);