Retrieve the id from Sequelize after executing a findOrCreate query

When attempting to create an associated table of tags with the id of a tag and the id of a related article, I encountered an issue. Despite successfully using the findOrCreate function to create a tag, the resulting id was null when trying to use it in my association with the tag's id as result.id. Strangely, while a simple create operation returns an id, findOrCreate does not. How can I retrieve the id of an entry created with the findOrCreate function? Additionally, I am open to exploring alternative methods for creating entries that do not already exist. Below is the code snippet from my app.js:

 function(sales, callback) {
      if(req.body.tags) {
            // Code block
      } 
 }

Here is the tag controller:

module.exports = {
    create(req, res, tag) {
        return Tags
          .findOrCreate({
            // Code block
   })
 }
};

And here is the tag model:

module.exports = (sequelize, DataTypes) => {
    // Code block
}

After further research and testing, I tried the following approach in my tag controller:

module.exports = {
    findOrCreate(req, res, tag) {
        return Tags
          .findOrCreate({
            // Code block
  }).spread((tags, created) => {
       console.log(tags.get({
          plain: true
       }))
  })
 }
};

While this successfully logs all created tags, I am facing difficulties in retrieving their ids. When attempting to return the ids instead of logging them, I only receive false results for tags that already exist in the database. I am currently stuck and seeking assistance on resolving this issue.

Answer №1

After some adjustment, I realized that returning the spread result directly wasn't working as expected, so I opted to insert it into a callback function. Here is my updated code:

  tagsController.findOrCreate(req, res, value).spread(function(tags, created){
                    if (created){
                        callback(null, tagSpottingController.create(req, res, tags.id, idCreation))
                    }
                    else {
                        callback(null, tagSpottingController.create(req, res, tags.id, idCreation))
                    }  
                 })

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

Encountering errors while attempting to share files in a system built with Node.js, Express,

This snippet shows my Node.js code for connecting to a database using Mongoose const mongoose = require('mongoose'); function connectDB() { // Establishing Database connection mongoose.connect(process see your Naughty's you're sure ...

What is the process for sending a request to a static resource along with parameters?

I currently have a node.js restify server running, along with a folder containing static resources. const restify = require('restify') let server = restify.createServer() server.listen(8080, function () { console.log('%s listening at ...

Leveraging the power of Ajax and Javascript to handle and process conditional if/else statements

Hey there, I'm new around here so I hope I got this right. Currently, I'm diving into the Ajax for Dummies book after enjoying the PHP one years ago. However, I've hit a roadblock with my first real Ajax program. It took me ages to locate th ...

Exploring the power of JavaScript Callback using nano and now.js

every.person.now.guessValue = function(value) { database.find('lists', 'project_names', { startingPoint: value, endingPoint: value + "\u9999" }, function(_, information) { return information.rows.map(function( ...

What is preventing me from accessing session data using nuxtServerInit?

When attempting to retrieve sessions, I encounter an issue. Is everything set up correctly in the following main files: server, config? store/index.js export const actions = { nuxtServerInit ({ commit }, { req }) { console.log(req); } The console log ...

How to retrieve an element using a dynamically generated class name in Vue.js

<v-data-table :headers="menuheaders" //this menus from api response :items="menus" item-key="usersmenu_menuid" items-per-page="1000" hide-default-footer="" class="elevation-1" > <template v-s ...

Display images in a rating system using Angular's ng-repeat directive

Need help with modifying star images based on ratings? I have two PNG files, one with an empty star and one with a full star. My goal is to dynamically adjust the number of stars displayed depending on the rating given, which ranges from 1 to 5. However, m ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Using jQuery to filter or duplicate options in a select box - a step-by-step guide!

I am struggling with filtering options in two select boxes. One contains projects and the other contains people: <select id="project"> <option data-person_ids="[75,76,77]">None</option> <option data-person_ids="[77]">Project A& ...

What are the possible reasons for my load function failing intermittently?

I have encountered an issue with my app where sometimes the content is not loaded into a dialog. Most of the time it works perfectly, but occasionally it fails to display the content. Here is the code snippet that I am using: $('#popup_background&apo ...

Executing the next function after promise() is not functioning properly in pure JavaScript

I'm completely new to Javascript development. CURRENT PROJECT - At the moment, I am immersed in developing a web chatbot application. AN ISSUE - I am encountering difficulties using the promise() function to execute more than one function sequential ...

Strategies for transferring retrieved data to the getServerSideProps function

I am currently utilizing the Context API to retrieve data and then pass that data to the getServerSideProps function, but encountering the following error: The React Hook "useContext" is being called in a function "getServerSideProps" that is neither a Re ...

A guide on extracting data from a JSON string and populating a list in JavaScript

Is there a way for me to extract the "Toppings" values from my JSON string and display them as list items? I appreciate any assistance you can provide! <html> <body> <section> <h2>Toppings</h2> <ul> <li>JSO ...

Enhance Your Webstorm Experience with Views Folder Autocomplete

My approach involves utilizing server rendering to deliver .html files from the /views directory, along with static assets from folders like /styles and /scripts within the app folder. Within my index.html file, I reference the stylesheet located in the / ...

Effective techniques for unit testing in Vue.js

Here's a question that's been on my mind: when it comes to unit testing in Vue.js, there are several different packages available. Vue Test Utils Vue Jest Vue Cypress For enterprise projects, which of these options would be considered best ...

What is Angular's approach to handling elements that have more than one directive?

When an element in Angular has multiple directives, each specifying a different scope definition such as scope:false, scope:true, or scope:{}, how does the framework handle this complexity? ...

How to Use JavaScript Function to Rotate an Entire Webpage

For my final project in a web design class, we were tasked with creating a website that showcases our skills. I've completed the assignment and now I want to add some interesting features to make it stand out. I'm interested in using -webkit-tra ...

An express.js mishap occurred when attempting to process an HTTP POST request using an AJAX client-side, resulting in a

Encountering a 500 Internal Server Error when attempting to send an HTTP POST request from client-side JavaScript using JQuery AJAX in Express.js. The code resides in the p.js file on the client. function dataHandler(conn,data) { var datalol=data; ...

Exploring the world of ASP .NET development with the powerful Sonar

We're currently working on an ASP .NET project and are looking for a way to analyze JavaScript files on-the-fly. Unfortunately, SonarLint only offers analysis for C# files. The incremental analysis feature seems to have been phased out, and issues ana ...

Show the present category name within breadcrumbs (utilizing angularJS)

Struggling to display category and vendor names on breadcrumbs? Utilizing the ng-breadcrumbs module but encountering difficulties in making curCategory and curVendor globally accessible. Tried various methods without success. Below is the HTML code snippe ...