Utilizing SequelizeJS to Pass an Array of Values

I am currently exploring the possibility of passing an array as the value for the property of an instance. In my model, I have set the dataType to STRING and I am inserting values from jQuery fields into an array which I then parse from the body and assign to the property discoverSource. However, I am encountering a string violation error stating that I cannot use an array or object. What does this error mean and how can I modify the dataType of the field or route to allow me to pass the comma separated values to the field?

For example, when passing values to the discoverySource field from two fields (NJ, NY), the values are combined in an array as ["NJ", "NY"] and the following error is displayed:

Error Message:

{"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"]}]}

Here is the model I am using:

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

Below is the route being used:

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

Here is the view file:

<!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>

Answer №1

In response to the previous comment, I have decided to enhance the code for better readability. Thus, I am sharing it in a new answer.

After some further consideration, I believe it would be more logical to implement it as a custom 'getter' function. Additionally, I will demonstrate how 'instanceMethods' can be included to illustrate how they function.

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

Both of these approaches add the functions to each instance that is created by the Model. The primary distinction lies in how they are accessed.

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

It is important to note the additional () required for the instanceMethod. These are included as functions of the instance, while the getterMethods are added as properties.

setterMethods operate in a similar manner, enabling you to define custom setters.

I hope this provides some clarification.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Image encoded in base64 not appearing on the screen

Hey there, I'm currently working on implementing a jQuery image uploader that generates a base64 code when an image is selected. function readImage(input) { if (input.files && input.files[0]) { var FR= new FileReader(); FR.onload ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Having difficulty executing a function inside a JavaScript file

Within my index.php file, the following lines of code are present: <!doctype html><html class=""><head><title>a title</title> <link href="_css/boilerplate.css" rel="stylesheet" type="text/css"> <script type="text/jav ...

The class is failing to be applied to the parent div that holds an id starting with the letter x

I have been attempting to assign a class to the parent container when the child element has the 'hidden' class. If not, then a different class should be added. function tagMissions() { if ($('span[id^="mission_participant_new"]').h ...

React app experiencing issues with Bootstrap offset functionality specifically when paired with a button element

I am struggling to position the button after two columns of space in this code snippet. Despite my efforts, the button remains pulled to the left and I can't seem to update it. { values.contact_persons_attributes.length < 2 && <div className= ...

Tips for inserting values into the initial row and column of a two-dimensional array using C

I am struggling with populating a 9x11 two-dimensional array in C with numbers ranging from 0 to 9 for rows and 0 to 11 for columns. I want the empty spaces to be filled with 0. After filling the empty blocks with zeros, here is the output: This is the c ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

socket.io allows for the reception of emit events from namespace that are dynamically created

Seeking help on how to send messages from my react client to express server using socket.io. This is the simplified Client code: import { useRef, useEffect } from 'react'; import io from "socket.io-client"; const Generator = () => ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

Having trouble establishing a connection with localhost at port 4445 using Nightwatch and Selenium

I am encountering an issue while trying to execute my Nightwatch script in Javascript. The error message I am receiving is: \ Connecting to localhost on port 4445... ‼ Error connecting to localhost on port 4445. × failed E ...

How can I resolve the problem of transferring retrieved data to a POST form?

When it comes to the form, its purpose is to send data fetched from another API along with an additional note. The fetched data was successfully received, as I confirmed by logging it to the console. It seems that the form is able to send both the fetche ...

Executing Code Upon Module Load and Presenting It as Middleware

I am currently delving into the intricacies of how exporting and importing modules function in Nodejs. One of my tasks involves using a specific file to seed a mongodb database. Surprisingly, this file operates flawlessly and delivers the desired results ...

Typescript: When using ts-node-dev, an error occurred while trying to import express due to an unexpected

I am embarking on a fresh project using Typescript and I intend to set up the node server with typescript utilizing express. There's a helpful tutorial that explains how to execute a Typescript file without going through the hassle of compiling files, ...

JavaScript - AngularJS HTML parser

I am working with an array that contains content along with HTML tags, and here is the code snippet: for (car in cars.parking[0]){ content.push('<br />'); for (token in cars.parking[0].now) { content.pus ...

`Using req.params in front-end JavaScript for successful data communication`

I am struggling to pass req.params data to the front-end and utilize it in various JavaScript functions. Unfortunately, I am unsure of how to access this data on the client side with JavaScript. My goal is to retrieve the req.param called 'namespace& ...

When switching back to the parent window and attempting to execute an action, a JavaScript error is encountered

Currently automating a SnapDeal eCommerce website A challenge I am facing is an error message in the console: The issue occurs when transitioning from a child window back to the parent window and performing operations on the parent window. //Automa ...

What is the proper way to safely escape a JSON string for an object that contains user-generated content?

How can I correctly use the variable s for the value-field of an option-element while escaping user input used for key and value? var key='highway'; var value='track'; var s = JSON.stringfy({ [key]:value }, undefined,''); s ...

Looking to pass multiple props and run a function for each one? Here's how!

There is a scenario where I have two separate times in minutes format that need to be converted to 24-hour format without separators. I am currently using a function for this conversion and then using momentjs to transform it into the required format. Whil ...

Ways to verify if a document is associated with another in MongoDB

Assume I am dealing with two collections: Users _id:5c810da8c714a02e84d16d16 username:foo Tokens _id: 5c81347b00370c2848db8725 _userId: 5c810da8c714a02e84d16d16 token: "83790bf08fa16eec1c3c6761d0c1be4f" I am attempting to validate if the token associa ...

Unlimited Lunch Options and Navigational Links

Looking for help with displaying the ul for MAINTENANCE and referencing specified classes from a CSS style sheet that are working elsewhere. However, the sub menu for MAINTENANCE is not showing up. Any suggestions? /* * Superfish v1.4.8 - jQuery menu w ...