使用 axios 将数据推送到现有对象中的数组



我有一个看起来像这样的对象:

{
"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。 而且我不知道该怎么做,当我使用axios.post时它会向我的episodes数组添加一个对象,如果我使用axios.put它会更改一个对象。是否有可能像我使用上面的代码那样将数据推送到数组,但使用 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);
}
};
};

但正如我所说,这确实向数组中添加了一个新对象.....

"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
}
]

所以为了清楚起见,我理解你的问题,你有一个数据库中已经存在的对象,你想把一些东西推到该现有对象的"字符"数组上,而不创建一个新对象,对吗?

为此,我将为您的数据库使用 Mongo 并定义两个 Mongoose 模式,一个用于现有对象(我们称之为 TVShow),另一个用于该对象中的字符。您的两个架构将如下所示:

TVShow型号.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 )

角色型号.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 发布请求。确保在将"value"变量发送到服务器时发送,它包含您将"推送"到的对象的id(或者可能是唯一的标题)。推送在 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)        
}
})

希望这是清楚的!

相关内容

  • 没有找到相关文章

最新更新