[英]Pushing data to an array in already existing object with axios
i have a object which looks like this:我有一个 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
}
to an characters
array i want to add the id
of characters.到一个characters
数组,我想添加字符的id
。 I do it by form
and then i handle submit
like this:我通过form
来做,然后我像这样handle submit
:
const handleSubmit = (values) => {
console.log("dodano aktora do filmu!");
console.log(values);
addActorToMovie(values);
history.goBack();
};
the addActorToMovie
action: addActorToMovie
动作:
export const addActorToMovie = (resp) => ({
type: types.ADD_CHAR_TO_MOVIE,
payload: resp,
});
and the reducer:和减速机:
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 };
}),
};
It all works, but the problem is that i dont want to do it loccaly.这一切都有效,但问题是我不想在当地做。 Im using an database
with json-server, and I want to do an Axios Request
so that it would add a data to the database
.我使用带有 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. 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. Is there any possibility to push the data to an array as i do it with the code above, but with axios so that it would be added to database
?是否有可能像我使用上面的代码一样将数据推送到数组,但是使用 axios 以便将其添加到database
中?
My approach looked like this:我的方法是这样的:
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);
}
};
};
but as I said this does add a new object to an array.....但正如我所说,这确实将新的 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
}
]
So just to be clear I understand your question, you have an object that already exists in your DB, and you want to push something onto the 'characters' array in that existing object, without creating a new object, correct?所以为了清楚我理解你的问题,你有一个 object 已经存在于你的数据库中,你想在现有的 object 中将一些东西推送到“字符”数组上,而不创建新的 ZA8CFDE6331BD59EB2AC96F8911C4B66,对吗?
To do this, I would use Mongo for your DB and define two Mongoose Schemas, one for the existing object (let's call it TVShow) and one for the Characters within that object.为此,我将为您的数据库使用 Mongo 并定义两个 ZCCADCDEDB567ABAE643E15DCF0974E503Z 模式,一个用于现有的 object(我们称之为 TVShow),另一个用于 object 中的字符。 Your two Schemas will look like this:您的两个架构将如下所示:
TVShowModel.js: 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: 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 )
Then, create your Axios post request.然后,创建您的 Axios 发布请求。 Make sure you send when you send the 'value' variable to your server, it contains the id (or perhaps the unique title) of the object you'll be 'pushing' to.确保在将“值”变量发送到服务器时发送,它包含您将“推送”到的 object 的 ID(或者可能是唯一标题)。 Push won't work in axios/react, so we'll use the 'spread' opperator instead. Push 在 axios/react 中不起作用,所以我们将使用 'spread' 运算符来代替。
Your router will look like this:您的路由器将如下所示:
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) } })
Hope this was clear!希望这很清楚!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.