gpt4 book ai didi

node.js - 在 Sequelize 和 postgres 中插入和获取 JSON 数据

转载 作者:行者123 更新时间:2023-12-03 22:25:57 26 4
gpt4 key购买 nike

在模型中

 {
data:{
type: Sequelize.JSONB
}
}

我是 Sequelize 的新手。
请任何人告诉我,如何在 sequelize 中插入和获取数据
提前致谢...

最佳答案

下面是一个例子:

import { sequelize } from '../../db';
import Sequelize, { Model } from 'sequelize';

class SomeModel extends Model {}
SomeModel.init(
{
data: {
type: Sequelize.JSONB,
},
},
{ sequelize, modelName: 'somemodels' },
);

(async function test() {
try {
await sequelize.sync({ force: true });
// insert
const data = { name: 'orm', age: 23 };
await SomeModel.create({ data });

// find
const row = await SomeModel.findByPk(1, { raw: true });
console.log(row);
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();

执行结果:

Executing (default): DROP TABLE IF EXISTS "somemodels" CASCADE;
Executing (default): DROP TABLE IF EXISTS "somemodels" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "somemodels" ("id" SERIAL , "data" JSONB, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'somemodels' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "somemodels" ("id","data") VALUES (DEFAULT,$1) RETURNING *;
Executing (default): SELECT "id", "data" FROM "somemodels" AS "somemodels" WHERE "somemodels"."id" = 1;
{ id: 1, data: { age: 23, name: 'orm' } }

数据库中的数据记录:

=# select * from "somemodels";
id | data
----+----------------------------
1 | {"age": 23, "name": "orm"}
(1 row)

关于node.js - 在 Sequelize 和 postgres 中插入和获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60705929/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com