简体   繁体   中英

Spread operator not working properly in javascript

I have a hasMany relation between the user and posts. In the code below I am trying to add posts to the userposts field of the user model if a post does not already exists. If a post already exists I basically want to update the userposts field with all the old posts and the new posts. userposts is a JSON field that exists in the user model. posted holds the value of the userposts field that exists in the user model.

When I add a new post I can see it being added in the userposts field but when I try to add more posts, In the database I get the userposts data as follows: ["Adding posts 2", "A", "d", "d", "i", "n", "g", " ", "p", "o", "s", "t", "s"]. I need it to be something like this ["Adding posts 2", "Adding posts"]

Why is this happening? How can I fix this?

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')
})

When adding the first post, you are setting it a single string instead of an array of strings. Thus, when you search for the user the next time, findUser.userposts is a string an not an array, and the spread operator does, what it's defined to do and splits the string into a char array.

Instead of using only req.body.postText as for the value of userposts on the first post, use an array containing that string as follows:

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}}
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM