Encountering a Sequelize error message that reads "Invalid value" while executing a basic query

After successfully creating a user with sequelize, I encountered an issue where querying any user resulted in an "Invalid value" error.

The Sequelize User model is defined as follows:

import DataTypes from "sequelize";
import bcrypt from "bcrypt";
import config from "../../config.js";

export default (sequelize) => {
  sequelize.define("user", {
    id: {
      primaryKey: true,
      type: DataTypes.INTEGER,
      allowNull: false,
      autoIncrement: true,
    },
    username: {
      type: DataTypes.STRING(25),
      allowNull: false,
      unique: true,
    },
    password: {
      type: DataTypes.STRING(60),
      allowNull: false,
      set(value) {
        this.setDataValue(
          "password",
          bcrypt.hashSync(value, config.saltRounds)
        );
      },
    },
    isAdmin: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
  });
};

Query used:

import { sequelize as db } from "./database/index.js";
import Op from "sequelize";
import bcrypt from "bcrypt";
import config from "./config.js";

const hashedPwd = bcrypt.hashSync("pass", config.saltRounds);

db.models.user
  .findOne({
    where: {
      [Op.and]: [{ username: "user" }, { password: hashedPwd }],
    },
  })
  .then((user) => {
    console.log(user);
    console.log(user.id)
  })
  .catch((err) => {
    console.log(err);
  });

Database entry can be viewed here.

Upon running the query, the result was:

> node .\test.js
Error: Invalid value { username: 'user' }
    at Object.escape (node_modules\sequelize\lib\sql-string.js:65:11)
    at MariaDBQueryGenerator.escape (node_modules\sequelize\lib\dialects\abstract\query-generator.js:995:22)
    at node_modules\sequelize\lib\dialects\abstract\query-generator.js:2572:69
    at Array.map (<anonymous>)
    at MariaDBQueryGenerator._whereParseSingleValueObject (node_modules\sequelize\lib\dialects\abstract\query-generator.js:2572:52)
    at MariaDBQueryGenerator.whereItemQuery (node_modules\sequelize\lib\dialects\abstract\query-generator.js:2354:19)
    at node_modules\sequelize\lib\dialects\abstract\query-generator.js:2259:25
    at Array.forEach (<anonymous>)
    at MariaDBQueryGenerator.whereItemsQuery (node_modules\sequelize\lib\dialects\abstract\query-generator.js:2257:35)
    at MariaDBQueryGenerator.getWhereConditions (node_modules\sequelize\lib\dialects\abstract\query-generator.js:2675:19)

Seeking insights on why every username queried triggers an "Invalid value" error.

Answer №1

To start off, make sure to import Op using the following syntax. It's not exported as a default.

import { Op } from 'sequelize';

Next, you can substitute top-level Op.and with the following:

db.models.user
  .findOne({
    where: {
      username: 'user',
      password: hashedPwd,
    },
  })

Lastly (unrelated to this issue), it's important to note that each call to bcrypt for hashing will yield a different result. This means that the where condition will never match. I suggest searching for a user by username/email and then verifying the password like so:

db.models.user.findOne({ where: { username: 'myUsername' } })
  .then((user) => {
    return bcrypt.compareSync('myPassword', user.password)
  })
  .then((isMatch) => {
    if (!isMatch) {
      throw new Error('UNAUTHORIZED') // or any other appropriate action
    }
  })

Answer №2

To start, make sure to import Op from sequelize by adding the following line of code:

import { Op } from 'sequelize';

Next, you can query the user using their unique field (such as email or phone number) like so:

db.models.user.findOne({
 where: {username: "username"}
})

This will return the user if they exist. Remember to verify their password with bcrypt as bcrypt generates different strings each time.

Answer №3

If you're facing a similar problem, double check that you are correctly placing elements in your code. Remember, an Include should not be within the Where statement but should instead be placed as a sibling to it.

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

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

Utilizing Mongoose to fetch data from Atlas MongoDB for integration into an Angular application

I recently made some updates to my signup page by adding a new input field for the user's name and adjusting the schema settings accordingly. How can I now retrieve this name to use in both my post-list component and post-create component? Here is an ...

In production, all Next.js API routes consistently return an "Interval Server Error," whereas in development, all routes operate smoothly without any issues

Every time I access any API route in my Next.js application in production, it results in a 500 "Internal Server Error". However, in development mode, all routes function smoothly and provide the expected output. https://i.stack.imgur.com/nPpeV.png https: ...

Using JavaScript, import the variable module object from a specific module

Is there a way to import a module object from a module if I am unsure of the specific objects I will need beforehand? How can I utilize a variable in place of fixed module names? import { dynamicVariable } from './module' The variable represents ...

Node and Express Issue: Index file failing to correctly call files

Greetings! In my Express project, my index file is where I bring in different files to kickstart my application. These include a database connection file, a logging file utilizing Winston, and a routes configuration file. Using the require() statement wit ...

What steps should be followed to execute this moment.js code in an Angular.js controller using Node.js?

I am trying to adapt the following node.js code that uses moment.js into an AngularJS controller: var myDate = new Date("2008-01-01"); myDate.setMonth(myDate.getMonth() + 13); var answer = moment(myDate).format('YYYY-MM-DD'); To achieve this, I ...

What is the best way to utilize functions in Express to dynamically display content on my Jade template?

I have successfully implemented a user registration and login page, but now I need to determine what content to display based on whether the user is logged in. I found this solution: app.use(function(req, res, next) { db.users.find({rememberToken: req.c ...

Guide to setting the connection string for connect-pg-simple

The example provided on https://github.com/voxpelli/node-connect-pg-simple illustrates the following code snippet: var session = require('express-session'); app.use(session({ store: new (require('connect-pg-simple')(session))(), ...

How can I add a subdocument to a MongoDB array based on a specific condition being met?

When pushing sub documents into an array, the structure of the subdocs typically looks like this: { id:"someId", date:Date } The goal is to only add a new subdoc if there isn't already another subdoc with a matching id. The $addToSet modifier in ...

Error: Unable to verify the user's identity. Mongoose

I have a node and MongoDB Docker application running on my local machine, but when I attempt to connect to the database using Mongoose, it gives me the following error: MongoError: Authentication failed. at MessageStream.messageHandler (D:\Node&bs ...

I am looking to serve static HTML files in Express.js while also retaining app.get() methods for handling server-side logic

It may sound trivial, but I am struggling with displaying HTML files within app.get() methods using Express. Most solutions I have found involve using app.use(express.static(__dirname + '/public'));, which limits server-side logic. What I want i ...

I'm encountering an operation timeout error in my sequelize connection. Any suggestions on how to resolve this issue?

Using Sequelize ORM in my NODE JS and PostgreSQL setup has been great, but recently I encountered an issue. When multiple requests are made to the server concurrently, an error is thrown: ConnectionAcquireTimeoutError [SequelizeConnectionAcquireTimeoutErro ...

Tips for transferring data from Express to .ejs file during redirection in Node.js

When I submit the login form in my login.ejs file, the page redirects if the details are correct. If the password is wrong, however, I want to display a message in the .ejs file indicating this. Below are the details: Here is the code in my app.js file - ...

Issues arise when attempting to delete messages that have already been retrieved

Having trouble removing messages from a specific user without any success: bot.js client.on("message", (message) => { if (message.content === '$deleteuser') { message.channel.fetchMessages({limit: 10}).then(collec ...

Encountering an issue when starting a Node.js/Swagger application using pm2 within a Docker environment: Unable to

1. Overview: I successfully developed a basic application using Node.js, Express, and Swagger by following this informative tutorial, along with the help of generator-express-no-stress. However, when I attempt to run the application within a Docker contai ...

How to integrate an AngularJS page into a Node application

Exploring the realm of single page web apps with node, angular, and jade has been an interesting journey for me as a newcomer to angular. I am currently faced with a dilemma regarding my app.js file - how can I ensure that my initial page template loads fr ...

I'm having trouble using Discord.js to set up a custom role with specialized permissions for muting users

module.exports = { name: "mute", description: "This command is used to mute members in a server", execute: async function (msg, arg) { const muteRole = await msg.guild.roles.cache.find((r) => r.name == "Mute ...

Building a CRUD application with Node.js and Sequelize ORM

In my quest for a straightforward illustration of how to implement CRUD code using the most up-to-date version 4.15 of Sequelize ORM, it was disheartening that I couldn't locate an all-inclusive solution. Consequently, I had to conduct individual sear ...

Utilizing NLP stemming on web pages using JavaScript and PHP for enhanced browsing experience

I've been exploring how to incorporate and utilize stemming results with JavaScript and PHP pages on web browsers. After running node index.js in the VS Code terminal, I was able to retrieve the output word using the natural library: var natural = re ...

"Exploring the dynamic capabilities of Node.JS and Java Publisher/Subscriber

I am working on developing an application where communication will be facilitated through a node.js server. This node server is responsible for receiving messages from other peers. Here is the code snippet for my node.js: var zmq = require('zmq&apos ...