gpt4 book ai didi

javascript - 展开运算符在 javascript 中无法正常工作

转载 作者:行者123 更新时间:2023-12-03 22:43:18 25 4
gpt4 key购买 nike

我在用户和帖子之间有一个 hasMany 关系。在下面的代码中,如果帖子不存在,我试图将帖子添加到用户模型的 userposts 字段。如果帖子已经存在,我基本上想用所有旧帖子和新帖子更新 userposts 字段。 userposts 是存在于用户模型中的 JSON 字段。 Posted 保存用户模型中存在的 userposts 字段的值。
当我添加一个新帖子时,我可以看到它被添加到 userposts 字段中,但是当我尝试添加更多帖子时,在数据库中我得到了 userposts 数据,如下所示:["Adding posts 2", "A", "d", "d", "i", "n", "g", "", "p", "o", "s", "t", "s"]。我需要它是这样的 [“添加帖子 2”,“添加帖子”]
为什么会这样?我怎样才能解决这个问题?

app.post('/topic', async (req,res) =>{

const availPosts = await Post.create({
text: req.body.postText,
UserId: req.body.UserId
})

const findUser = await User.findOne({
where: {id:req.body.UserId}
})

// Code runs when posts already exists
const posted = findUser.userposts // holds the value of a user's post

if(posted){
const newPost = ([req.body.postText, ...posted])
let updatedPosts = await User.update({userposts:newPost },
{ where: {id: req.body.UserId}},
)
}
else {
let updatedPosts = await User.update({userposts:req.body.postText },
{ where: {id: req.body.UserId}},
)
}

res.send('working')
})

最佳答案

添加第一篇文章时,您将其设置为单个字符串而不是字符串数组。因此,当您下次搜索用户时, findUser.userposts 是一个字符串而不是一个数组,并且扩展运算符执行它定义的操作并将字符串拆分为一个字符数组。
在第一篇文章中,不要只使用 req.body.postText 作为 userposts 的值,而是使用包含该字符串的数组,如下所示:

if(posted){
const newPost = ([req.body.postText, ...posted])
let updatedPosts = await User.update({userposts:newPost },
{ where: {id: req.body.UserId} }
)
}
else {
let updatedPosts = await User.update({userposts: [req.body.postText] }, //use array here, instead of string
{ where: {id: req.body.UserId}}
)
}

关于javascript - 展开运算符在 javascript 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66132443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com