Sequelize JSON data type

前端 未结 5 750
北荒
北荒 2021-02-02 14:22

I have defined a model as

module.exports = function (sequelize, DataTypes) {
  const MyModel = sequelize.define(\'MyModel\', {
    data: {
      type: DataTypes         


        
5条回答
  •  情深已故
    2021-02-02 14:41

    The easiest solution is to use this little library called sequelize-json

    Create a database and a Schema:

    var Sequelize = require('sequelize'),
      JsonField = require('sequelize-json'),
      db,
      User;
    
    db = new Sequelize('database', 'username', 'password', {
      dialect: 'sqlite',
      logging: false
    });
    
    User = db.define('User', {
      username: Sequelize.STRING,
      jsonField: JsonField(db, 'User', 'jsonField')
    });
    

    Note the parameters of JsonField, you pass your Sequelize instance, the name of the model, and the name of the field. A little awkard, but this is needed in order to add the proper hooks to the model instance.

    Now, you can always treat that field as a json object:

    User.create({
          username: 'Scott',
          jsonField: {
            likes: ['running', 'node']
          }
        })
        .then(function(user) {
          user.jsonField.likes.push('tests');
          return user.save();
        })
        .then(function(user) {
          expect(user.jsonField).to.be.a('object');
          expect(user.jsonField.likes).to.have.length(3);
        });
    It will work with normal save commands, as well as updateAttribute commands.

提交回复
热议问题