node.jsexpressmongoose-schema

I am facing weird error while redirecting url in Node.js


I am trying to create a URL shortener using Node.js. I have set up a POST request that generates a random ID
This request takes a redirect URL. while creating a GET request to redirect to the original URL using the short ID, I am encountering a weird error. Whenever I change the name of the variable that extracts the short ID from the URL (req.params.shortId) and ensure to update the search string in the findOneAndUpdate() method accordingly, I get a null entry (resulting model).

20: app.get("/:shortId", async(req, res) => {
21:    const shortId = req.params.shortId;
22:    const entry = await URL.findOneAndUpdate(
23:      {
24:        shortId  // if changed here and in line 20: 'const shortId'
25:                // to any other name entry becomes null why?
26:      },
27:    res.redirect(entry.redirectURL); //redirecting to the original URL
28:  });

Solution

  • You seem to be confused by the syntax findOneAndUpdate({ shortId })

    This is actually short for findOneAndUpdate({ shortId: shortId }) and is looking for database entries where the field shortId is the specified variable value.

    If you change the variable name in the short form notation ("shorthand properties", if you need something to google) to myShortId, you are looking for database entries, where the field myShortId is the specified variable value. (yielding no results unless you happen to also have a field with that name).

    If you instead use the long notation, you can rename the variable:

    const myShortId = req.params.shortId;
    const entry = await URL.findOneAndUpdate({shortId: myShortId});
    

    note that the object key is still shortId, so the correct DB field is searched.