【问题标题】:Post an array of strings within a state object from React to MongoDB将状态对象中的字符串数组从 React 发布到 MongoDB
【发布时间】:2019-09-07 13:35:36
【问题描述】:

我有一个像这样的猫鼬 userSchema:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true,
    required: true,
    maxlength: 32
  },
  email: {
    type: String,
    trim: true,
    required: true,
    unique: 32
  },
  hashed_password: {
    type: String,
    required: true
  },
skills: {
     type: Array,
     default: [],
     required: true
   }
}, {timestamps: true});

skills 字段是一个数组。理想情况下,我想在用户输入时动态呈现文本输入,以便用户可以输入任意数量的技能。

将技能输入到每个单独的文本输入中,我想将它们中的每一个连接到一个数组中,然后通过 POST 请求发送到数据库。

我该怎么做?

这是我没有数组输入的代码:

发布请求

const signup = (user) => {
    fetch(`${API}/signup`, {
      method: "POST",
      headers: {
        Accept: 'application/json',
        "Content-Type": "application/json"
      },
      body: JSON.stringify(user)
    })
    .then(response => {
      return response.json();
    })
    .catch(err => {
      console.log(err);
    });
  };

const clickSubmit = event => {
    event.preventDefault();
    signup({name, email, password, studying});
  };

在没有动态 skills 输入的情况下反应 DOM

const signUpForm = () => (
    <form>
        <div className="form-group">
            <label className="text-muted">Name</label>
            <input onChange={handleChange('name')} type="text" className ="form-control" />
        </div>

        <div className="form-group">
            <label className="text-muted">Email</label>
            <input onChange={handleChange('email')} type="email" className ="form-control" />
        </div>

        <div className="form-group">
            <label className="text-muted">Password</label>
            <input onChange={handleChange('password')} type="password" className="form-control" />
        </div>

        <div className="form-group">
            <label className="text-muted">Studying</label>
            <input onChange={handleChange('studying')} type="text" className ="form-control" />
        </div>

        <button onClick={clickSubmit} className="btn btn-primary">
          Sign Up
        </button>
    </form>
  );

【问题讨论】:

    标签: node.js reactjs mongodb mongoose mongoose-schema


    【解决方案1】:

    您可以通过以下方式更改您的模型

    const userSchema = new mongoose.Schema({
      name: {
        type: String,
        trim: true,
        required: true,
        maxlength: 32
      },
      email: {
        type: String,
        trim: true,
        required: true,
        unique: 32
      },
      hashed_password: {
        type: String,
        required: true
      },
    skills: {[
        //add the field you want , For example :- `in : {type: String , default: null}`
        required: true
       ]}
    }, {timestamps: true});
    

    这将帮助您解决问题。

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 2020-07-19
      • 2022-01-14
      • 2020-11-27
      相关资源
      最近更新 更多