SequelizeJS传递值数组

时间:2016-01-28 01:23:03

标签: javascript arrays express sequelize.js

我试图弄清楚如何将数组作为实例属性的值传递。我目前在我的模型中将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>

1 个答案:

答案 0 :(得分:1)

要回答最后一条评论,我需要能够使代码更具可读性,因此我将在新答案中将其发布到此处。

考虑到这一点,将它添加为定制的“吸气剂”会更有意义。功能。我还会包含&#39; instanceMethods&#39;以及如何发挥作用。

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');
        }
    }
});

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

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

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

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

希望能澄清一点。