I have a simple Express/Pug app that is supposed to allow me to search users in a database by “email” and by “key.” In this schema, a key is simply a string that each user is assigned. My user model and index model files look like this:
models/index.js:
const dbConfig = require("../config/db.config.js"); const Sequelize = require("sequelize"); const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, { host: dbConfig.HOST, dialect: dbConfig.dialect, pool: { max: dbConfig.pool.max, min: dbConfig.pool.min, acquire: dbConfig.pool.acquire, idle: dbConfig.pool.idle } }); const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.users = require("./users.model.js")(sequelize, Sequelize); module.exports = db;
models/users.model.js:
module.exports = (sequelize, Sequelize) => { const User = sequelize.define("users", { email: { type: Sequelize.STRING, allowNull: false, unique: true, validate: { isEmail: { msg: "Must be a valid email address", }, }, }, key: { type: Sequelize.STRING, }, wallet_address: { type: Sequelize.STRING, }, createdAt: { type: Sequelize.DATE, field: "created_at", }, updatedAt: { type: Sequelize.DATE, field: "created_at", }, }); return User; };
My controller file looks like this:
controllers/users.controllers.js:
const db = require("../models"); const User = db.users; const Op = db.Sequelize.Op; exports.findAll = (req, res) => { const email = req.query.email; var condition = email ? { email: { [Op.iLike]: `%${email}%` } } : null; console.log(email); console.log(condition); User.findAll({ where: condition }) .then((data) => { res.send(data); }) .catch((err) => { res.status(500).send({ message: err.message || "Some error occurred while retrieving users.", }); }); }; // Create and Save a new User exports.create = (req, res) => { // Validate request if (!req.body.email) { res.status(400).send({ message: "Content can not be empty!" }); return; } // Create a User const user = { email: req.body.email, key: req.body.key, wallet_address: req.body.wallet_address }; // Save User in the database User.create(user) .then(data => { res.send(data); }) .catch(err => { res.status(500).send({ message: err.message || "Some error occurred while creating the User." }); }); }; exports.findbykey = (req, res) => { const key = req.body.key; var condition = key ? { key: { [Op.iLike]: `%${key}%` } } : null; console.log(key); console.log(condition); User.findAll({ where: condition }) .then((data) => { res.send(data); }) .catch((err) => { res.status(500).send({ message: err.message || "Some error occurred while retrieving users.", }); }); }
My users route looks like this:
routes/users.js:
var express = require('express'); var router = express.Router(); const users = require("../controllers/users.controller.js"); /* GET all registered users */ router.get("/registered", users.findAll); /* GET users by key */ router.get("/specuser", users.findbykey); /* POST user to database */ router.post("/addsubmit", users.create); module.exports = router;
And my index route file looks like this:
var express = require('express'); var router = express.Router(); const users = require("../controllers/users.controller.js"); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); /* GET user creation page */ router.get('/adduser', function(req, res, next) { res.render('adduser'); }); module.exports = router;
I currently have 2 entry’s in my postgres database and the raw output of my db looks like this:
[ { "id": 1, "email": "test@example.com", "key": "trythis1", "wallet_address": "trythisss2", "createdAt": "2022-07-09T08:29:02.747Z", "updatedAt": "2022-07-09T08:29:02.747Z" }, { "id": 2, "email": "test2@example.com", "key": "trythis1g", "wallet_address": "trythisss2g", "createdAt": "2022-07-09T13:46:52.261Z", "updatedAt": "2022-07-09T13:46:52.261Z" } ]
The /registered
route works perfectly when I search by email. This is an example of running this route and searching for test@example.com
.
Notice above that only the first and correct db entry is displayed
But… when I try to run the /specuser
route and search by key, the app incorrectly spits out all entries.
The source of the problem is that req.body.key
isn’t being recognized in exports.findbykey
. I tried to log key
and condition
in my users.controllers.js
file
const key = req.body.key; var condition = key ? { key: { [Op.iLike]: `%${key}%` } } : null; console.log(key); console.log(condition);
But I found undefined
for key and null
for condition in my terminal. So how can I get this findbykey
function to properly find the user by key?
Advertisement
Answer
Unlike findAll
, which uses req.query.email
, findbykey
uses req.body.key
. In order to use req.body
, you must include a body-parsing middleware like express.urlencoded({extended: false})
.