[英]Pushing data to an array in already existing object with axios
我有一个 object,它看起来像这样:
{
"title": "675756",
"release_date": "2022-01-16",
"series": "Better Call Saul",
"img": "https://upload.wikimedia.org/wikipedia/en/0/03/Walter_White_S5B.png",
"characters": [],
"id": 1
}
到一个characters
数组,我想添加字符的id
。 我通过form
来做,然后我像这样handle submit
:
const handleSubmit = (values) => {
console.log("dodano aktora do filmu!");
console.log(values);
addActorToMovie(values);
history.goBack();
};
addActorToMovie
动作:
export const addActorToMovie = (resp) => ({
type: types.ADD_CHAR_TO_MOVIE,
payload: resp,
});
和减速机:
case types.ADD_CHAR_TO_MOVIE:
console.log(action.payload);
return {
...state,
...state.episodes.map(function (item) {
return item.id === action.payload.episodeId
? {
id: item.id,
title: item.title,
release_date: item.release_date,
series: item.series,
img: item.img,
characters: [...item.characters, action.payload.actor],
}
: { ...item };
}),
};
这一切都有效,但问题是我不想在当地做。 我使用带有 json-server 的database
,我想做一个Axios Request
,以便它将数据添加到database
中。 And i don't know how to do this, when i use axios.post
it adds an object to my episodes
array, if im using axios.put
it changes an object. 是否有可能像我使用上面的代码一样将数据推送到数组,但是使用 axios 以便将其添加到database
中?
我的方法是这样的:
export const addActorToMovieAxios = (value) => {
console.log(value);
return async (dispatch) => {
try {
const response = await axios.post(
`http://localhost:3000/episodes/`,
value
);
console.log(response);
dispatch(addActorToMovie(response.data));
} catch (ex) {
console.log(ex);
}
};
};
但正如我所说,这确实将新的 object 添加到数组中......
"episodes": [
{
"title": "675756",
"release_date": "2022-01-16",
"series": "Better Call Saul",
"img": "https://upload.wikimedia.org/wikipedia/en/0/03/Walter_White_S5B.png",
"characters": [],
"id": 1
},
{
"episodeId": 1,
"actor": "1",
"id": 2
}
]
所以为了清楚我理解你的问题,你有一个 object 已经存在于你的数据库中,你想在现有的 object 中将一些东西推送到“字符”数组上,而不创建新的 ZA8CFDE6331BD59EB2AC96F8911C4B66,对吗?
为此,我将为您的数据库使用 Mongo 并定义两个 ZCCADCDEDB567ABAE643E15DCF0974E503Z 模式,一个用于现有的 object(我们称之为 TVShow),另一个用于 object 中的字符。 您的两个架构将如下所示:
TVShowModel.js:
const mongoose = require('mongoose'); const CharacterModel = require('./CharacterModel') const TVShowScheme = new mongoose.Schema({ title: { type: String, }, release_date: { type: Date, }, series: { type: String, }, img: { type: String, }, characters:[ { type: mongoose.Schema.Types.ObjectId, ref: 'Student' }, ], examQuestions: [ { type: mongoose.Schema.Types.ObjectId, ref: 'CharacterModel' } ] }) module.exports = mongoose.model('TVShowModel', TVShowScheme )
CharacterModel.js:
const mongoose = require('mongoose'); const CharacterModel= new mongoose.Schema({ characterName: { type: String, }, actorName: { type: String, }, }) // add any other fields you want here module.exports = mongoose.model('CharacterModel', CharactModelScheme )
然后,创建您的 Axios 发布请求。 确保在将“值”变量发送到服务器时发送,它包含您将“推送”到的 object 的 ID(或者可能是唯一标题)。 Push 在 axios/react 中不起作用,所以我们将使用 'spread' 运算符来代替。
您的路由器将如下所示:
const CharacterModel= require ('../models/CharacterModel'); const TVShowModel= require ('../models/TVShowModel'); const router = express.Router(); router.post('/episodes', async function(req,res){ try{ const tvshow = await TVShowModel.find({title: req.body.title}) // edit as needed console.log("FOUND TV Show: "+tvshow ) const characterName= req.body.characterName const actorName = req.body.actorName const newCharacter = new CharacterModel({ characterName, actorName, }) console.log("new character created: "+newCharacter) tvshow[0].CharacterModel = [...tvshow[0].CharacterModel,newCharacter]; await tvshow[0].save().then(()=>res.json('New Character Added to DB')).catch(err=>res.status(400).json('Error: ' + err)) } catch(e){ console.log(e) } })
希望这很清楚!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.