SequelizeJS 传递值数组

SequelizeJS Passing Array of Values

我想弄清楚如何将数组作为实例 属性 的值传递。我目前在我的模型中将 dataType 设置为 STRING 并将 jQuery 字段中的值插入每个表单字段值到我从主体解析并设置为 属性、discoverSource。不幸的是,我收到一个字符串违规错误,提示我无法使用数组或对象。这是什么意思,如何更改字段或路由的 dataType 以允许我将逗号分隔值传递给字段?

E.x。对于 discoverySource,我将值传递给两个字段(NJ、NY)。提交时,这些值组合在一个数组中作为 ["NJ", "NY"] 并且错误显示:

错误信息:

{"name":"SequelizeValidationError","message":"string violation: discoverySource cannot be an array or an object","errors":[{"message":"discoverySource cannot be an array or an object","type":"string violation","path":"discoverySource","value":["NJ","NY"]}]}

这是我的模型:

module.exports = function(sequelize, DataTypes) {

var Organization = sequelize.define('organization', {
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        autoIncrement: true,
        primaryKey: true
    },
    organizationName: {
        type: DataTypes.STRING,
        field: 'organization_name'
    },
    admin: DataTypes.STRING,
    discoverySource: {
        type: DataTypes.TEXT,
        field: 'discovery_source'
    },
    members: DataTypes.STRING
},{
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
        },
    },
});
    return Organization;
}

这是路线:

var express = require('express');
var appRoutes   = express.Router();
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
var models = require('../models/db-index');

appRoutes.route('/sign-up/organization')

    .get(function(req, res){
        models.User.find({
            where: {
                user_id: req.user.email
            }, attributes: [ 'user_id', 'email'
            ]
        }).then(function(user){
            res.render('pages/app/sign-up-organization.hbs',{
                user: req.user
            });
        })  
    })

    .post(function(req, res, user){
        models.Organization.create({
            organizationName: req.body.organizationName,
            admin: req.body.admin,
            discoverySource: req.body.discoverySource
        }).then(function(organization, user){
            res.redirect('/app');
        }).catch(function(error){
            res.send(error);
            console.log('Error at Post' + error);
        })
    });

这是我的视图文件:

<!DOCTYPE html>
<head>
    {{> head}}
</head>
<body>
    {{> navigation}}
    <div class="container">
        <div class="col-md-6 col-md-offset-3">
            <form action="/app/sign-up/organization" method="post">
                <p>{{user.email}}</p>
                <input type="hidden" name="admin" value="{{user.email}}">
                <input type="hidden" name="organizationId">
                <label for="sign-up-organization">Company/Organization Name</label>
                <input type="text" class="form-control" id="sign-up-organization"  name="organizationName" value="" placeholder="Company/Organization">
                <a href="#" id="sign-up-add-discovery-source">Add Another Discovery Source</a>
                <div id="sign-up-organization-discovery-source">
                    <input type="text" id="discovery-source-field" placeholder="Discovery Source" name="discoverySource[0]">
                </div>
                <br />
                    <button type="submit">Submit</button>
            </form>
            <a href="/login">Already have an account? Login here!</a>
        </div>
    </div>
    <script type="text/javascript">
        $(function() {
  var dataSourceField = $('#sign-up-organization-discovery-source');
  var i = $('#sign-up-organization-discovery-source p').size();
  var sourceCounter = 1;

  $('#sign-up-add-discovery-source').on('click', function() {
    $('<p><label for="discovery-source-field"><input type="text" id="discovery-source-field" size="20" name="discoverySource['+ sourceCounter++ +']" value="" placeholder="Discovery Source" /></label> <a href="#" class="remove">Remove</a></p>').appendTo(dataSourceField);
    i++;
    return false;
  });
  $('#sign-up-organization-discovery-source').on('click', '.remove', function() {
    if (i > 1) {
      $(this).parent('p').remove();
      i--;
    }
    return false;
  });
});

    </script>
</body>

为了回答最后一条评论,我需要能够使代码更具可读性,所以我将其发布在一个新的答案中。

再考虑一下,将其添加为自定义 'getter' 函数会更有意义。我还将包括 'instanceMethods' 来演示它是如何工作的。

var Organization = sequelize.define('organization', {
    ...
},{
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Organization.belongsToMany(db.User, { through: 'member', foreignKey: 'user_id' });
        },
    },
    // Here's where custom getters would go
    getterMethods: {
        discoverySources: function() { 
            return this.getDataValue('discoverySource'); 
        }
    },
    // here's the instance methods
    instanceMethods: {
        getSourcesArray: function() {
            return this.getDataValue('discoverySource');
        }
    }
});

这两个选项都将函数添加到模型创建的每个实例中。主要区别在于它们的访问方式。

organization.discoverySources; // -> ['s1', 's2', etc...]
organization.getSourcesArray(); // -> ['s1', 's2', etc...]

请注意 instanceMethod 所需的额外 ()。这些被添加为实例的函数,getterMethods 被添加为属性。

setterMethods 以相同的方式工作以允许您定义自定义设置器。

希望能澄清一些事情。