
[英]Sequelize.js - model association during “create” or “build” call
[英]How to create an endpoint in Sequelize.js that receives any random JSON in the model?
我使用 Sequelize 和 Postgresql 在 Express 服务器上创建了一个简单的端点。 这个端点应该接收一个简单的 POST 请求,其中 JSON Object 将事件注册为回调。 问题是,这将是一个 JSON object 有很多字符串和数字,我无法为其编写特定的 model。
我目前的 model 有两个问题。
我只能接收指向 Event.event 的事件,而实际上我想接收不应以关键“事件”开头的任何 JSON,就像我在 model 上写的那样。 但是,我实际上并不知道如何创建一个 model,它允许我们将任何未指定的 JSON 发送到我的表事件。
如果我收到那些试图将 JSON 发布到此端点的回调,它们自然会以 NULL 的形式出现,因为它们不适合 Event.event
这是 model:
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;
我的实际问题是如何编写一个 model 来接收发送到该端点的任何类型的未指定 JSON ?
例如:
{
AnyRandomJSON: {type: Sequelize.JSON, allowNull: False}
}
实际上不必给它起“事件”之类的名称,而只需接收发送到“/ event-receiver”的任何内容并在我的 postgresql 上名为“事件”或“数据”的特定列上注册,诸如此类。
通过阅读文档和其他相关的帮助文章并不能启发我如何以简单的方式做到这一点。
在存储来自 Yelp 的餐厅的 JSON 数据时,我遇到了类似的问题。 虽然数据是 JSON,但其结构无关紧要。
为了避免不兼容(一些 SQL 引擎不支持 JSON),我最终将其存储为Sequelize.TEXT
:
restaurant_yelp_info: Sequelize.TEXT()
您命名该列的名称并不重要。
如有必要,我在存储前使用JSON.stringify()
转换为 JSON。
检索后,我使用JOSN.parse()
将 JSON 转换为 object。
最后,我设法通过向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);
});
用我的 Model 使用 JASONB
const Event = sequelize.define(
'Events',
{
Data:
{
type: Sequelize.JSONB,
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.