pg-promise makes it easy to use named parameters with nested objects

Is it feasible to access nested objects while utilizing named parameters in pg-promise? Take a look at this example:

var obj = {
    name: 'John',
    address: {
        postcode: 'abc'
    }
};

db.query('SELECT * FROM users WHERE postcode=${address.postcode} AND name=${name}', obj);

Currently, the nested object reference does not get resolved with the actual value. For instance, ${address.postcode} remains unchanged and not replaced by 'abc' in the query string.

Answer №1

Please be aware: This particular answer is no longer applicable following the release of v6.10.0 for pg-promise, as it now has built-in support for Nested Named Parameters.

The code example mentioned in the original question will now function correctly without any alterations.


Specifically for usage with pg-promise versions earlier than v6.10.0

It's important to note that the library solely formats Named Parameters and does not evaluate them, hence direct evaluation, as shown, is not possible within the library. However, you can achieve similar functionality by making sub-properties accessible to the query-formatting engine through defined functions:

var obj = {
    name: 'John',
    address: {
        postcode: 'abc'
    },
    addrCode: a => a.address.postcode // utilizing an alias for sub-property access
};

You can then utilize WHERE postcode = ${addrCode}.

Additionally, the older / ES5 syntax using this is also viable:

var obj = {
    name: 'John',
    address: {
        postcode: 'abc'
    },
    addrCode: function(/*a*/) {
        // a = this (both can be used)
        return this.address.postcode;
    }
};

UPDATE

It's now feasible to incorporate client-side evaluations, however, only with $1, $2, ... parameters:

db.query('... postcode = $1 AND name = $2', [obj.name, obj.address.postcode]);

Remember, utilizing evaluations like ${obj.address.postcode} within the query string directly is not recommended, as it may lead to incorrect escaping of values.

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

Count up with style using the "jQuery Boilerplate" plugin for Jquery!

I am a beginner in creating jQuery plugins. The following jQuery plugin has been created using jQuery Boilerplate. It performs a count-up and notifies when the count-up is completed. I would like to have a function that restarts the count-up by setting t ...

Uploading an image using Vue.js

Currently, I am utilizing the ElementUi uploader and facing an issue where the file details are not being sent correctly to the back-end along with my form data: Screenshots When I select an image, here is the console log: https://i.sstatic.net/StfNl.pn ...

CSS ID selectors are not functioning properly

In my React.JS project, I am working with a div that contains a button and a list. The list is specifically identified by the id "results". return <div> <Button label="Combine Cards" disabled={!this.props.combineReady} onClick={this.handleCli ...

Review Limited Screen Size for a Smartphone Website

I have been working on optimizing a mobile website and I utilized CSS to adjust the layout design for screen widths between 150px and 480px. However, during testing on an actual phone, the desktop layout is appearing instead of the custom layout set with C ...

What is the best way to incorporate async/await in a useEffect hook in a React Native application?

Upon executing useEffect, my objective is to retrieve the token from AsyncStorage, fetch the data value using the axios.post('/auth/me') endpoint, and trigger the KAKAOLOG_IN_REQUEST action through dispatch. After verifying that the data value i ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

Utilizing $index in AngularJS while iterating through ng-repeat items

Here is an example of an unordered list: <ul class="dropdown-menu inner" role="menu"> <li ng-repeat="availableAlphaName in availableAlphaNames" data-original-index="0" data-optgroup="1" class=""> <a tabindex="0" class="opt " st ...

Quickest method for deriving a boolean value from multiple boolean inputs

Within a document, the keys isOccupied and vacant are being destructured. const { isOccupied, vacant } = doc || {}; boolDetermination = (isOccupied, vacant) => { if (isOccupied && isOccupied === vacant) { < --- Return isOccupied value ...

`Incorporating dynamic link filtering in vis.js`

Can links and nodes be filtered in a vis.js network? I have configured a DataSet for both nodes and edges as follows: function drawNetwork(container){ var nodes = new vis.DataSet(); populateNodes(nodes); // implementation details skipped ...

Why aren't the kittens loading in Next Js?

Following the guidance in the Next Js documentation, I created a next.config.js file to inform Next Js that I want to incorporate kittens into my app. The resource for the kittens can be found at: This is how the next.config.js file appears: module.expor ...

Unable to execute focus() - query not functioning

In my code, I have an input field and I am trying to invoke it in my js file. $(document).ready(function () {$('#input_id').focus(); }); However, the focus is not working as expected. Even when I try to trigger it manually in my Chrome console, ...

Reposition the initial element to the end of an array using setInterval() within a React component

I'm attempting to rearrange the elements in an array in React, specifically by moving the first item to the last position using a setInterval function: const [cardOrder, setCardOrder] = useState([card1, card2, card3, card4]); setInterval(() => { ...

Invoke the function when the user inputs text into the textbox

<textarea name="" id="" #text cols="30" (keydown)="WordCounter()" (change)="WordCounter()" rows="8" [(ngModel)]="user_text" placeholder="Type something here"></textare ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...

Tips for preventing a component from updating state prior to data retrieval?

I have a specific scenario where I am working with a page that consists of two components. In this setup, I am retrieving data from the root component and passing it to the child component using the react-redux library. However, I encountered an issue wher ...

Choosing KineticJS path based on its identification number

I've been working on creating an interactive map using some prebuilt templates. Each country in the map highlights when the mouse hovers over it. My question is, how can I make another country, like Brazil, highlight when any country is hovered over? ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

Utilizing the Jquery ready method in conjunction with the load function

While utilizing the ready() method to access the DOM, I encountered an issue where jQuery was returning undefined when trying to access an element. Even after nesting the ready() function inside $(window).on("load", function()), there were still instances ...

Each time guildMemberAdd is triggered in Discord.js, it may not run consistently

At times, I am left baffled by the inconsistency in behavior of this code. Sometimes it works like a charm, while other times it refuses to add people for hours on end, only to randomly start working again. Any suggestions on how I can resolve this issue? ...