我已经使用Sequelize和Postgresql在Express服务器上创建了一个简单的端点。该端点应该接收一个简单的POST请求,其中包含一个JSON对象,该对象将事件注册为回调。问题是,这将是一个包含大量字符串和数字的JSON对象,我无法为其编写特定的模型。
我现在的模型有两个问题。
我只能接收定向到Event.event的事件,而实际上我想接收任何不应该以我在模型中编写的关键“事件”开头的JSON。然而,我实际上并不知道如何创建一个允许我们将任何未指定的JSON发送到我的表事件的模型。
如果我收到那些试图将JSON发送到这个端点的回调,它们自然会变成NULL,因为它们不适合Event.event
这是一个模型:
const Sequelize = require('sequelize');
const sequelize = require('../db');
const Event = sequelize.define(
'Event',
{
event: {type: Sequelize.JSON, allowNull: false}
}
);
module.exports = Event;和路由器:
const { Router } = require("express");
const Event = require("./model");
const router = new Router();
router.get("/event-receiver", (req, res, next) => {
const limit = req.query.limit || 25;
const offset = req.query.offset || 0;
Event.findAll({ limit, offset })
.then(allEvents => res.json(allEvents))
.catch(next);
});
router.post("/event-receiver", (req, res, next) => {
Event.create(req.body)
.then(newEvent => res.status(201).json(newEvent))
.catch(next);
});
module.exports = router;我的实际问题是,我如何编写一个模型,该模型接受发送到该端点的任何类型的未指定JSON?
例如:
{
AnyRandomJSON: {type: Sequelize.JSON, allowNull: False}
}实际上不必给它起一个像"event“这样的名字,而只是简单地接收发送到"/event-receiver”的任何东西,并在我的postgresql上注册一个名为Events或Data的特定列,任何类似的东西。
通过阅读文档和其他相关帮助文章,我并不知道如何以一种简单的方式做到这一点。
发布于 2020-07-13 23:01:05
最后,我设法通过向Event.create()添加一个数据来修复它。比我想的容易多了。
router.post("/signrequest-event-receiver", (req, res, next) => {
Event.create({
Data: req.body
})
.then(console.log(req.body))
.then((newEvent) => res.status(201).json(newEvent))
.catch(next);
});我的模型使用JASONB
const Event = sequelize.define(
'Events',
{
Data:
{
type: Sequelize.JSONB,
}
}
);发布于 2020-04-09 00:16:32
在Yelp上存储餐馆的JSON数据时,我遇到了类似的问题。虽然数据是JSON,但其结构无关紧要。
为了避免不兼容(一些SQL引擎不支持JSON),我最终将其存储为Sequelize.TEXT
restaurant_yelp_info: Sequelize.TEXT()列的名称并不那么重要。
如有必要,我会在存储之前使用JSON.stringify()转换为JSON。
在检索之后,我使用JOSN.parse()将JSON转换为对象。
https://stackoverflow.com/questions/61103514
复制相似问题