如何插入一个包含自动生成值的列的表,例如" createdAt" && 34; updatedAt"?

时间:2018-01-10 20:13:55

标签: node.js postgresql express sequelize.js

我很擅长使用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 setup(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;

2 个答案:

答案 0 :(得分:1)

你可以使用sequelize hooks。 beforeCreate有一个可用于在插入之前添加/更改值。例如;

User.beforeCreate((user, options) => {
  return hashPassword(user.password).then(hashedPw => {
    user.password = hashedPw;
  });
});

请参阅 http://docs.sequelizejs.com/manual/tutorial/hooks.html

答案 1 :(得分:1)

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

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