My goal is to send distinct entries for each user that accesses the system from a MySQL database

As a beginner, I need help figuring out how to send each logged-in user a list of unique records from the database. I want to ensure that no duplicate records are sent to different users. How can I achieve this? Below is the code snippet responsible for fetching records from the database:

phrases.findAll({
      where: {
         userId: user.id,
         phraseStatus: 1
      },
      limit: 10,
      offset: 10
   })
   .then((data) => {
      userObj.phrases.push(...data);

      return res.status(200).json(userObj);
   });

Answer №1

Keeping track of what messages have been sent to other users is crucial. I recommend creating a table called phrases_sent to maintain a record of all sent phrases. Make sure to include the phrase_id in this table to establish a relationship.

For guidance on associations, refer to the documentation at this link.

To retrieve phrases that have not been sent yet, you can execute a query that outer joins the phrases_sent table with the phrases table.

Here's an example:

    const unusedPhrases = await sequelize.models.phrase.findAll({
        where: {
            '$phrasesSents.phrase_id$': {[Op.is]: null}
        },
        attributes: ['phrase.phrase'],
        include: [
            {
                attributes: [],
                model: sequelize.models.phrasesSent,
                required: false,
            }
        ],
        raw: true,
        nest: true
    });

This query will result in:

SELECT "phrase"."phrase" 
FROM "phrases" AS "phrase" 
LEFT OUTER JOIN "phrases_sent" AS "phrasesSents" ON "phrase"."id" = "phrasesSents"."phrase_id" 
WHERE "phrasesSents"."phrase_id" IS NULL;

Using a LEFT OUTER JOIN is generally more efficient than using a NOT IN (SELECT ...) approach for performance reasons.

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

Exploring the possibilities of implementing the .map() function on a JSONArray within a ReactJS project using ES

When I receive a JSONArray from the server, my goal is to use .map() on it in order to extract key-value pairs of each object within the array. However, when I try to implement this code, I encounter an error stating "files.map is not a function". Can some ...

ReactJS import duplication problem arising from utilizing npm link for component testing prior to npm package release

I have a basic component structured like this. import React, {useState} from 'react'; function MyComponentWithState(props) { const [value, setValue] = useState(0); return ( <p>My value is: {value}</p> ) } expo ...

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

Is it possible to deploy a Google App Engine service that relies on a local npm package?

I am currently navigating my way through Google Cloud and facing challenges with deploying a Google App Engine service that relies on a local sibling dependency. My project structure follows this format (using TypeScript, nestJS, React): -frontend app ...

Is it a cookie-cutter function?

Can someone help me solve this problem: Implement the special function without relying on JavaScript's bind method, so that: var add = function(a, b) { return a + b; } var addTo = add.magic(2); var say = function(something) { return something; } ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

What is the method for retrieving the index of an array from an HTML element?

Howdy! Within my Vue application, I have the ability to create multiple individuals: <div v-for="newContent in temp" :key="newContent.id" @click="showId(newContent.id)" v-show="true"> <!-- ...

Ways to prevent other users from clicking or modifying a particular row

I have a data table in my project that will be accessed by multiple users simultaneously. My requirement is that once a row is selected and edited by one user, it should become unclickable for other users who are also viewing the same page or data table. ...

Is it possible for JavaScript to access and read a local file from a web page hosted locally

I am interested in using html, css, and javascript to develop a user interface for configuring a simulation. This interface will be used to generate a visualization of the simulation and an output parameters file based on multiple input files. It is impor ...

Guide to creating an uncomplicated quiz using PHP

My goal is to create a quiz with 15 questions. Every time a user lands on the page, they will see a random selection of 5 questions. Each question will have 4 multiple choice answers, with one being correct. The marks allocated for each question are 20, 15 ...

Creating Layouts with Bootstrap 3

I'm exploring the codepen below in an attempt to mimic the appearance of the image provided consistently across all screen sizes. However, there are two issues that I am encountering - firstly, the green numbers on the first line which represent the d ...

Strategies for avoiding a hover component from causing distortion to its parent component in React

I am encountering an issue with a hover component that is causing distortion in its parent component when displayed. Essentially, I need to prevent the hover component from affecting the layout of its container. Below is the code snippet: Styling for Lang ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

using an array as an argument in an express POST request

I am currently exploring express-validator, and I came across a specific example in the documentation that caught my attention. The example code snippet is as follows: const { check, validationResult } = require('express-validator/check'); app. ...

Vulnerability protection against AngularJS JSON is not removed

I am currently working on an Angular app that communicates with an API. The JSON responses from the API are prefixed with )]}', as recommended in Angular's official documentation. The issue I am facing is that my browser seems to try decoding th ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Ways to retrieve information from a $$state object

Everytime I try to access $scope.packgs, it shows as a $$state object instead of the array of objects that I'm expecting. When I console log the response, it displays the correct data. What am I doing wrong? This is my controller: routerApp.controll ...

Steps to transfer text from one input field to another by clicking a button using JavaScript

Hello, I am new to Javascript so please forgive me if my question seems silly. I have been tasked with creating a form containing two input fields and a button. When the button is clicked, the text entered in the first field should move to the second field ...

Implementing slideDown() functionality to bootstrap 4 card-body with jQuery: A step-by-step guide

Here is the unique HTML code I created for the card section: <div class="row"> <% products.forEach(function(product){ %> <div class="col-lg-3 col-md-4"> <div class="card mb-4 shadow "> &l ...

Managing two separate instances with swiper.js

Currently, I have set up two instances of swiper.js and I am looking to scroll both while interacting with just one of them. Update: My primary objective is to replicate the core functionality seen on the swiper homepage. Update 2: I came across this lin ...