"An issue has been encountered with lastID being undefined while using sqlite3 with Node

After successfully inserting into the database, I am encountering an issue where this.lastID is undefined. Can anyone help me troubleshoot this code?

app.post('/products/create', (req,res) => {
    
    upload(req, res, (err) => {
        const name = req.body.name
        const description = req.body.description
        const Filename = req.file.filename
        const id = this.lastID
        console.log(id)
        //console.log('Selected Files: ' + req.Filename);
        db.uploadPost(name, description, Filename, function(error){
            if(error){
                console.log(err)
            }
            else{
                console.log(this.lastID)
                res.redirect('/products/'+id)
            }
        })
    })
})

In addition, here is my database logic:

exports.uploadPost = function(name, description, Filename, callback){
        const query = "INSERT INTO products('name', 'description', 'image') VALUES (?,?,?)"
        const values =  [name, description, Filename]
        db.run(query,values, function(error){
            callback(error)
        })
    }

Answer №1

When utilizing the upload method, it is important to note that the property this.lastID is not accessible due to the insertion query being executed at a later stage.

An effective solution would involve the following implementation:

exports.uploadPost = function(name, description, Filename, callback){
    const query = "INSERT INTO products('name', 'description', 'image') VALUES (?,?,?)"
    const values =  [name, description, Filename]
    db.run(query,values, function(error){
        callback(error, this.lastID) // passing the computed lastID as a parameter of the callback
    })
}

To further adapt the code:

app.post('/products/create', (req,res) => {

    upload(req, res, (err) => {
        const name = req.body.name
        const description = req.body.description
        const Filename = req.file.filename
    
        db.uploadPost(name, description, Filename, function(error, id){
            if(error){
                console.log(err)
            }
            else{
                // utilize the provided id here, once the insertion query has been successfully executed
                console.log(id)
                res.redirect('/products/'+id)
            }
        })
    })
})

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

Issue arises with asynchronous function outside of mounted lifecycle hook in VueJS

Identifying the Issue I encountered an issue while trying to create an external async function and assign its return value directly to a state variable. In addition, I passed firebase reference and store to this function to avoid importing them again in t ...

Display a child component in a Vue template

Is there a way to display one of $children in the current vue template? Let's say I have three $children components, is it feasible to render this.$children[1]? The appearance of this.$children[1] is as follows: https://i.sstatic.net/8KzYJ.png ...

Exploring the MVC viewBag concept in Express.js

Currently, I am working with express js 4.1 and handlebars template 4.0. In the process of rendering a page, I am passing a collection of objects from an express route.get('/') to a handlebar(.hbs) view file. I am wondering if there is a way to s ...

Is the API for remote asynchronous http calls (Ajax) in Vuejs comparable to that of jQuery?

While Vuejs is known for being more effective than jQuery for DOM manipulation and user interactions handling, I am curious about its performance when it comes to remote asynchronous HTTP (Ajax) calls. I'm looking for a specific Vue.js core API that c ...

Having trouble establishing a connection between MongoDB and a Node.js Express server on my local machine

While attempting to establish a connection between mongoDB and nodejs express using the post method, I added a logger that should display a message confirming that the database is connected once nodejs listens to mongoDB. However, I encountered an issue wh ...

Are the methods of implementing a modal in JavaScript, HTML, and CSS similar to those in Electron JS?

Struggling to implement a button that triggers a modal display using JavaScript? The HTML and CSS components are set up correctly, but the JavaScript functionality seems to be causing issues. Is it possible that Electron JS differs from traditional JavaScr ...

Implement jQuery on Multiple Elements

My task involves populating a dynamically changing table with data that contains an unknown number of rows. Each row consists of a hyperlink, which when clicked, displays more details about that specific row. What I want to achieve is to attach a single j ...

Instructions on toggling button visibility based on dropdown selection?

My goal is to have a button hidden by default, and when I select an option from a dropdown list, the button should appear. Check out the code on JSFIDDLE $(function() { $('#cashbill').change(function() { $('#bill_icon').hide() ...

How can I implement callback functions in joi validation?

Exploring the World of Coding I came across a code snippet online that caught my attention, but upon closer inspection, I realized it used Hapi/Joi which is now considered outdated. My question is how can I modify this code to work with Joi? app.post(&apo ...

Tips for incorporating web fonts into designMode

I am currently working with a text editor that has the ability to use designMode along with an <iframe>. My goal is to change the font to a Google Web font. Below is the JavaScript code I am using: function setFont(fontName, boolValue, fontText) { ...

What causes the unique transformation of text by Chrome when displayed over a canvas element?

It appears that when text is placed on top of a canvas element, Chrome enforces hardware-accelerated transforms. Could someone provide insight into this behavior? My goal is to resize text over a canvas element without it being transformed into a texture. ...

Receiving Output from an AJAX Request

My PHP script is set up to verify the validity of an email address, returning either true or false. I've been attempting to use AJAX to call this PHP file and pass the result back to a Javascript function, but unfortunately, I haven't been succes ...

Issue with attaching dynamic events is not functioning as expected

var smartActionsId = ['smartActions1','smartActions5','smartActions10']; for (let i in smartActionsId) { console.log("smartActionsId ="+smartActionsId[i]); $('#' + smartActionsId[i] + ' select').c ...

Building a scrollable dropdown menu with Bootstrap 5: A step-by-step guide

The search for suitable code examples for scrollable dropdown menus compatible with Bootstrap 5 has been challenging. Are there any contemporary methods available to achieve this functionality seamlessly? ...

I defined a `const` within the `this.api.getApi().subscribe(({tool,beauty})` function. Now I'm trying to figure out how to execute it within an `if`

I've recently set up a const variable within this.api.getApi().subscribe(({tool,beuty}). Now, I'm trying to figure out how to run it within an if statement, just like this: if (evt.index === 0) {aa} I plan on adding more similar lines and I need ...

What methods can I use in Mocha with Sinon for testing multiple callbacks?

My code involves a function with asynchronous operations and multiple callbacks var f = (cb1, cb2) => { return new Promise((resolve, reject) => { /* ... */ }); }; During testing, I wanted to use sinon to create spies var cb1Spy = sinon.spy(); va ...

Heroku local is designed to support only NodeJS applications, without any Angular framework or database connectivity

I'm currently facing two separate issues. When I run my app locally, it works fine, but it doesn't function properly on Heroku. Running "heroku local" opens the NodeJS app on localhost:5000 and connects to the local database. However, when attemp ...

Errors in socket.on Listeners Result in Inaccurate Progress and Index Matching for Multiple Video Uploads

Is there a way to make sure that the `socket.on('upload-progress')` listener accurately updates the upload progress for each video as multiple videos are uploaded simultaneously? Currently, it appears that the listener is updating the progress fo ...

The Angular event handler fails to trigger change detection upon clicking

I am facing a simple problem where I have an element in a component's template with an ngIf condition and a (click) handler. Initially, the element is not rendered because the ngIf condition evaluates to false. What makes this interesting is that an ...

Setting the useState hook to a User type in React - the ultimate guide!

As someone new to hooks, I'm unsure about what the initial value for useState should be set to. Currently, an empty object is set as the default value for useState with const [user, setUser] = useState({}); This is causing ${crafter.id} to throw an e ...