Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
扩展运算符在javascript中工作不正常_Javascript_Mysql_Arrays_Database_Sequelize.js - Fatal编程技术网

扩展运算符在javascript中工作不正常

扩展运算符在javascript中工作不正常,javascript,mysql,arrays,database,sequelize.js,Javascript,Mysql,Arrays,Database,Sequelize.js,我在用户和帖子之间有很多关系。在下面的代码中,如果帖子不存在,我将尝试向用户模型的userposts字段添加帖子。如果一篇文章已经存在,我基本上想用所有旧文章和新文章更新userposts字段。userposts是用户模型中存在的JSON字段。posted保存用户模型中存在的userposts字段的值 当我添加一个新帖子时,我可以看到它被添加到userposts字段中,但当我尝试添加更多帖子时,我在数据库中得到如下userposts数据:[添加帖子2,a,d,d,I,n,g,p,o,s,t,s]

我在用户和帖子之间有很多关系。在下面的代码中,如果帖子不存在,我将尝试向用户模型的userposts字段添加帖子。如果一篇文章已经存在,我基本上想用所有旧文章和新文章更新userposts字段。userposts是用户模型中存在的JSON字段。posted保存用户模型中存在的userposts字段的值

当我添加一个新帖子时,我可以看到它被添加到userposts字段中,但当我尝试添加更多帖子时,我在数据库中得到如下userposts数据:[添加帖子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是一个字符串而不是一个数组,而spread运算符执行定义的操作,并将字符串拆分为一个字符数组

对于第一篇文章的userposts值,不要只使用req.body.postText,而是使用包含该字符串的数组,如下所示:

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

似乎const post不是数组而是字符串。因此,spread运算符将其扩展到一个charsAll数组,周围的代码是无关的。这里唯一相关的是post的值,您还没有提供。如果它真的是JSON,那么这就解释了它。JSON是文本。描述没有帮助。我要求提供一个确切的例子。问题是如何添加第一篇文章。可能您正在将第一篇文章添加为字符串,而不是数组,这样做:是的,就是这样。请看,userposts首先为null,然后我们使用Post.create添加posts,然后使用添加的posts更新用户模型的userposts字段。这就是我想要达到的目标