我正在尝试按 id 查找帖子并为其添加评论。
我正在使用 postgreSQL。
这是我的模型
const Sequelize = require('sequelize')
const db = require('../../config/database')
const Posts =db.define("Topics",{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
title : {
type : Sequelize.STRING,
},
description : {
type: Sequelize.STRING
},
username : {
type: Sequelize.STRING
},
comment : {
type:Sequelize.ARRAY(Sequelize.STRING),
defaultValue : [],
allowNull: false
}
})
module.exports = Posts;
这是我的nodeJS 请求。
app.put('/addComment/:id', (req, res) => {
Posts.update({
comment: req.body.comment
},
{
where: {
id: req.params.id
}
}).then((post) => {
res.send(post)
}).catch((err) => {
console.log("err", err);
});
})
我正在使用邮递员测试我的服务器,但每当我尝试将更新的数据发送到数据库时,我总是收到此错误
err TypeError: values.map is not a function
。
请问您对如何解决这个问题有什么建议吗? 另外,在我的数据库中,注释数组的数据类型是
text[]
我也尝试将update
更改为create
但没有结果
您已在字符串数组类型的模型中定义了注释,但在更新时您直接传递单个字符串,请以数组格式传递
Posts.update({
comment: [req.body.comment] // note the square brackets for array
},
{
where: {
id: req.params.id
}
}).then((post) => {
res.send(post)
}).catch((err) => {
console.log("err", err);
});
我通过将
req.body.comment
更改为 [req.body.comment]
解决了该问题。
检查您的 req.body.comment 并将其作为数组发送
req.body.comment = ['test']
您需要将
req.body.comment
数据解析为数组使用 JSON.parse()
示例:
JSON.parse(req.body.comment)
参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse