axios 没有将数组保存到 MongoDB

Posted

技术标签:

【中文标题】axios 没有将数组保存到 MongoDB【英文标题】:axios is not saving an Array in to MongoDB 【发布时间】:2019-10-21 10:21:24 【问题描述】:

我正在尝试在axios 的帮助下将subjects 中的array 与其他数据一起传递给MongoDB

问题是 (axios) 没有将 subject array 保存到 MongoDB

这是我的AddCourse.jx

import React, Component from 'react';
import axio from 'axios';

export default class AddCourse extends Component

    constructor(props)
        super(props);
        this.state = 
            colorChange: true,
            coloChangeTwo: true,
            courseName: '',
            courseCode: '',
            passMarks: '',
            lectureInCharge: '',
            subjects: []

        ;

    

    onClick()
        this.setState(
            colorChange: !this.state.colorChange
        );

        if(this.state.colorChange)

            this.state.subjects.push('1');

        else
            var search_term = '1';
            for(var i = this.state.subjects.length-1; i>=0; i--)
                if(this.state.subjects[i] === search_term)
                    this.state.subjects.splice(i, 1);
                    break;
                
            
        
    
    onClick2()
        this.setState(
            coloChangeTwo: !this.state.coloChangeTwo
        );
        if(this.state.coloChangeTwo)

           this.state.subjects.push('2');

        else
            var search_term = '2';
            for(var i = this.state.subjects.length-1; i>=0; i--)
                if(this.state.subjects[i] === search_term)
                    this.state.subjects.splice(i, 1);
                    break;
                
            
        
    

    onSubmit(e)
        e.preventDefault();

        //new course object
        const newCourse = 
            courseName: this.state.courseName,
            courseCode: this.state.courseCode,
            passMarks: this.state.passMarks,
            lectureInCharge: this.state.lectureInCharge,
            subjects: this.state.subjects
        ;
        // console.log(this.state.subjects);
        // console.log(newCourse);

        axio.post('http://localhost:4000/course/add', newCourse)
            .then((res) => 
                console.log('Course ' + res + ' Added!');
            ).catch((err) => 
                console.log(err);
        );

        this.setState(
            colorChange: true,
            coloChangeTwo: true,
            courseName: '',
            courseCode: '',
            passMarks: '',
            lectureInCharge: '',
            subjects: []
        );

    

    onChangeCourseName(e)
        this.setState(
            courseName: e.target.value
        );
    
    onChangeCourseCode(e)
        this.setState(
            courseCode: e.target.value
        );
    
    onChangePassMarks(e)
        this.setState(
            passMarks: e.target.value
        );
    
    onChangeLectureInCharge(e)
        this.setState(
            lectureInCharge: e.target.value
        );
    

    render() 

        let beforeClickingButton = 'btn btn-warning';
        let afterClickingButton = 'btn btn-secondary';
        let subjectButtonClass1 = this.state.colorChange ? beforeClickingButton : afterClickingButton;
        let subjectButtonClass2 = this.state.coloChangeTwo ? beforeClickingButton : afterClickingButton;

        return(
            <div>
                <h1>Add Course</h1>
                <br />

                <form onSubmit=this.onSubmit.bind(this)>
                    <div className="container">

                        <div className="form-group">
                            <label>Course Name:</label>
                            <input
                                value=this.state.courseName
                                onChange=this.onChangeCourseName.bind(this)
                                type="text" className="form-control" placeholder="Course Name" />
                        </div>

                        <div className="form-group">
                            <label>Course Code:</label>
                            <input
                                value=this.state.courseCode
                                onChange=this.onChangeCourseCode.bind(this)
                                type="text" className="form-control" placeholder="Course Code" />
                        </div>

                        <div className="form-group">
                            <label>Pass Mark</label>
                            <input
                                value=this.state.passMarks
                                onChange=this.onChangePassMarks.bind(this)
                                type="text" className="form-control" placeholder="Pass Mark"/>
                        </div>

                        <div className="form-group">
                            <label>Lecture In Charge:</label>
                            <input
                                value=this.state.lectureInCharge
                                onChange=this.onChangeLectureInCharge.bind(this)
                                type="text" className="form-control" placeholder="Lecture in Charge"/>
                        </div>

                        <div className="form-group">
                            <label>Subjects: Select Subjects from below... (Green = Not Selected/Grey = Selected)</label>
                            <div className="container">
                                <div className="row text-center">
                                    <div className="col-6">
                                        <button
                                            onClick=this.onClick.bind(this)
                                            className=subjectButtonClass1
                                            type="button" >Computer Architecture</button>
                                    </div>
                                    <div className="col-6">
                                        <button
                                            onClick=this.onClick2.bind(this)
                                            className=subjectButtonClass2
                                            type="button">Computer Networking</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="form-group">
                            <button type="submit" className="btn btn-success btn-lg">Save Course</button>
                        </div>

                    </div>
                </form>
            </div>
        );
    

这是我在节点环境中的server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const CourseDB = require('./course-dbmodel');

const PORT = 4000;

const app = express();
const router = express.Router();

app.use(bodyParser.json());
app.use(cors());
app.use('/course', router);

mongoose.connect('mongodb://127.0.0.1:27017/course', useNewUrlParser: true);
const connection = mongoose.connection;
connection.once('open', () => 
    console.log('MongoDB connected through the port 27017');
);

app.listen(PORT, () => 
    console.log('Listening to port 4000');
);

//add course
//http://localhost:4000/course/add
router.route('/add').post((req, res) => 
    let courseDb = new CourseDB(req.body);
    courseDb.save().then(course => 
        res.status(200).send('Added!');
    ).catch(err => 
        console.log(err);
    );
);

//get all courses
router.route('/all').get((req, res) => 
    CourseDB.find((err, course) => 
        if(err) throw err;
        res.status(200).send(course);
    );
);

//get books by course name
router.route('/:courseName').get((req, res) => 
    let courseName = req.params.courseName;
    CourseDB.find(subject: $regex: `$courseName`,(err, subjects) => 
        if(err) throw err;
        res.status(200).send(subjects);
    )


);

这是mongoose database schema,我用来将值存储到MongoDB

const mongoose= require('mongoose');
const Schema = mongoose.Schema;

let CourseDb = new Schema(
    courseName: type: String,
    courseCode: type: String,
    passMarks: type: Number,
    lectureInCharge: type: String,
    subject: [type: String]
);

module.exports = mongoose.model('CourseDb', CourseDb, 'CourseDb');

谁能告诉我我做错了什么?

我在数据库中的数据的屏幕截图

这是当我consolo.log()newCourse 对象时

【问题讨论】:

您能否尝试在 /add 路由上以及在 axios 帖子之前放置 console.log 以检查 subject 值。 是的,会上传截图 完成!检查我的更新答案@niccord 好的,服务器日志呢? subject 更改为subjects 看起来你在服务器端忘记了s 【参考方案1】:

在你的架构中试试这个:

替换

subject: [type: String]

subject: [String]

我会写这篇评论,但我没有评论权!

https://mongoosejs.com/docs/schematypes.html#arrays

【讨论】:

以上是关于axios 没有将数组保存到 MongoDB的主要内容,如果未能解决你的问题,请参考以下文章

Laravel VueJS Axios 将数组发送到控制器

使用 Vue.js + axios 将本地图像链接到 api 数组

如何使用 axios 将数组从 javascript 传递到 laravel 控制器

Vue Js 在我用 Axios get 调用的函数内部,将传入的数据打印到数组中

axios.put 保存为字符串

axios不发出请求,没有结果,没有错误