gpt4 book ai didi

node.js - 如何 INSERT 到包含自动生成值(如 "createdAt"和 "updatedAt")的列的表?

转载 作者:行者123 更新时间:2023-11-29 14:33:37 24 4
gpt4 key购买 nike

我刚开始使用 express.js 和 postgresql 开发 API。

我只是想插入一个表,但不知道这样做的合适方法。

我正在尝试做的请求:(在我知道其他列是自动创建之前,我创建了一个列 'dateCreated')

router.post('/', (req, res, next) => {
models.sequelize.query("INSERT INTO carts ("dateCreated") VALUES (?,?,?)").then(() => {
console.log("done")
});
});

PSQL 购物车表

PSQL output

购物车型号:

module.exports = (sequelize, DataTypes) => {
const Cart = sequelize.define("cart", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
dateCreated: DataTypes.STRING
});
return Cart;
}

Sequelize 设置(index.js):

const Sequelize = require('sequelize');

const sequelize = new Sequelize('shoptest', 'neymgm', 'password', {
dialect: 'postgres',
operatorsAliases: false,
// logging: true
})

const models = {
Cart: sequelize.import('./cart'),
CartItem: sequelize.import('./cartItem'),
Product: sequelize.import('./product'),
};

Object.keys(models).forEach((modelName) => {
if ('associate' in models[modelName]) {
models[modelName].associate(models);
}
});

models.sequelize = sequelize;
models.Sequelize = Sequelize;

module.exports = models;

最佳答案

试试这个……它会自动生成dateCreated

module.exports = (sequelize, DataTypes) => {
const Cart = sequelize.define("cart", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
}
}, { dateCreated: 'Created'});
return Cart;
}

关于node.js - 如何 INSERT 到包含自动生成值(如 "createdAt"和 "updatedAt")的列的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48195355/

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