如何从React前端将数组发送到MongoDB后端

huangapple go评论64阅读模式
英文:

How to send an array from a react Frontend to a mongo DB BackEnd

问题

以下是翻译好的部分:

在Postman中,我成功地通过这种方式发送数据来维护这个结构:{"categoryTags":["easy", "breakfast"]},这将创建一个看起来像这样的结构:categoryTags: 0:"easy", 1:"breakfast"。这对于后续在我的前端上进行映射非常有用。当在前端检索到信息时,它会以这种方式到达:easy, breakfast,当编辑并推送到数据库时,它看起来像这样:categoryTags:0:"easy,breakfast"。我不知道如何从前端到后端维护这个结构。这是否可能?

这是我的React代码:

const EditRecipeModal = ({ recipe }) => {
  const oneRecipe = useSelector((state) => state.user.singleRecipe);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchSingleRecipe(recipe._id));
  }, []);

  const [tags, setTags] = useState([recipe.categoryTags]);
  const [title, setTitle] = useState(recipe.title);
  const [description, setDescription] = useState(recipe.description);
  const [ingredients, setIngredients] = useState(recipe.ingredients);
  const [instructions, setInstructions] = useState(recipe.instructions);

  const editedModal = {
    categoryTags: tags,
    title: title,
    description: description,
    ingredients: ingredients,
    instructions: instructions,
  };

  const onSubmitHandler = (e) => {
    e.preventDefault();
    dispatch(editRecipe(editedModal, `${recipe._id}`));
  };

  return (
    <div id="editRecipeModal">
      <h1>Edit {recipe.title}</h1>
      <div>
        <form onSubmit={onSubmitHandler}>
          <label className="fw-bold">Category</label>
          <input
            onChange={(e) => setTags(e.target.value)}
            value={tags}
            type="text"
            placeholder={recipe.categoryTags}
          />
          <Form.Group className="mb-3">
            <Form.Label className="fw-bold">Title</Form.Label>
            <Form.Control
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              type="text"
              placeholder="ingredients"
            />
          </Form.Group>
          <Form.Group className="mb-3">
            <Form.Label className="fw-bold">Ingredients</Form.Label>
            <Form.Control
              value={ingredients}
              onChange={(e) => setIngredients(e.target.value)}
              type="text"
              placeholder="ingredients"
            />
          </Form.Group>
          <Form.Group className="mb-3">
            <Form.Label className="fw-bold">Instructions</Form.Label>
            <Form.Control
              value={instructions}
              onChange={(e) => setInstructions(e.target.value)}
              type="text"
              placeholder="instructions"
            />
          </Form.Group>
          <Button
            className="login-80p mb-4 fw-bold"
            variant="success"
            type="submit"
          >
            Edit
          </Button>
        </form>
      </div>
      <Button variant="danger">Delete</Button>
    </div>
  );
};
export default EditRecipeModal;

这是我的后端模式:

const recipeSchema = new Schema({
  categoryTags: [{ type: String, required: true }],
  title: { type: String, required: true },
  photo: {
    type: String,
    required: false,
    default: "https://cdn-icons-png.flaticon.com/512/135/135161.png",
  },
  description: { type: String, required: false },
  ingredients: [{ type: String, required: false }],
  instructions: [{ type: String, required: false }],
  author: { type: Schema.Types.ObjectId, ref: "User", required: true },
});

export default model("Recipe", recipeSchema);
英文:

I have been building a recipe app (both front and back end). My issue is with the data structure and how to maintain it.

My recipe schema has a few properties that have an array of objects as values. On Postman, I am able to successfully maintain this structure by sending it like this {"categoryTags":["easy", "breakfast"]} and this creates a structure that looks like This: categoryTags: 0:"easy", 1:"breakfast"... This is great for mapping later on my frontend. The Information when retrieved on the frontend arrives like this: easy,breakfast and when edited and pushed to the db... it looks like this: categoryTags:0:"easy,breakfast". I don't know how to maintain the structure from the FE to the BE. Is this possible?

This is My React Code:

const EditRecipeModal = ({ recipe }) =&gt; {
const oneRecipe = useSelector((state) =&gt; state.user.singleRecipe);
const dispatch = useDispatch();
useEffect(() =&gt; {
dispatch(fetchSingleRecipe(recipe._id));
}, []);
const [tags, setTags] = useState([recipe.categoryTags]);
const [title, setTitle] = useState(recipe.title);
const [description, setDescription] = useState(recipe.description);
const [ingredients, setIngredients] = useState(recipe.ingredients);
const [instructions, setInstructions] = useState(recipe.instructions);
const editedModal = {
categoryTags: tags,
title: title,
description: description,
ingredients: ingredients,
instructions: instructions,
};
const onSubmitHandler = (e) =&gt; {
e.preventDefault();
dispatch(editRecipe(editedModal, `${recipe._id}`));
};
return (
&lt;div id=&quot;editRecipeModal&quot;&gt;
&lt;h1&gt;Edit {recipe.title}&lt;/h1&gt;
&lt;div&gt;
&lt;form onSubmit={onSubmitHandler}&gt;
&lt;label className=&quot;fw-bold&quot;&gt;Category&lt;/label&gt;
&lt;input
onChange={(e) =&gt; setTags(e.target.value)}
value={tags}
type=&quot;text&quot;
placeholder={recipe.categoryTags}
/&gt;
&lt;Form.Group className=&quot;mb-3&quot;&gt;
&lt;Form.Label className=&quot;fw-bold&quot;&gt;Title&lt;/Form.Label&gt;
&lt;Form.Control
value={title}
onChange={(e) =&gt; setTitle(e.target.value)}
type=&quot;text&quot;
placeholder=&quot;ingredients&quot;
/&gt;
&lt;/Form.Group&gt;
&lt;Form.Group className=&quot;mb-3&quot;&gt;
&lt;Form.Label className=&quot;fw-bold&quot;&gt;Ingredients&lt;/Form.Label&gt;
&lt;Form.Control
value={ingredients}
onChange={(e) =&gt; setIngredients(e.target.value)}
type=&quot;text&quot;
placeholder=&quot;ingredients&quot;
/&gt;
&lt;/Form.Group&gt;
&lt;Form.Group className=&quot;mb-3&quot;&gt;
&lt;Form.Label className=&quot;fw-bold&quot;&gt;Instructions&lt;/Form.Label&gt;
&lt;Form.Control
value={instructions}
onChange={(e) =&gt; setInstructions(e.target.value)}
type=&quot;text&quot;
placeholder=&quot;instructions&quot;
/&gt;
&lt;/Form.Group&gt;
&lt;Button
className=&quot;login-80p mb-4 fw-bold&quot;
variant=&quot;success&quot;
type=&quot;submit&quot;
&gt;
Edit
&lt;/Button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;Button variant=&quot;danger&quot;&gt;Delete&lt;/Button&gt;
&lt;/div&gt;
);
};
export default EditRecipeModal;

This is my BE Schema:

const recipeSchema = new Schema({
categoryTags: [{ type: String, required: true }],
title: { type: String, required: true },
photo: {
type: String,
required: false,
default: &quot;https://cdn-icons-png.flaticon.com/512/135/135161.png&quot;,
},
description: { type: String, required: false },
ingredients: [{ type: String, required: false }],
instructions: [{ type: String, required: false }],
author: { type: Schema.Types.ObjectId, ref: &quot;User&quot;, required: true },
});
export default model(&quot;Recipe&quot;, recipeSchema);

答案1

得分: 1

你可以将BE模式中的categoryTags定义为数组类型 { type: Array, required: true }

英文:

you can define the categoryTags in the BE schema as array type { type: Array, required: true }

huangapple
  • 本文由 发表于 2023年3月4日 04:50:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631765.html
  • javascript
  • mongodb
  • react-redux
  • reactjs

如何在没有填充的情况下,从文本到

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定