Setting Collection variable programmatically

I tried using the pm.collectionVariables.set() method to set a collection variable that shares the same variable name with an environment variable from my pre-request script.

The pre-request script runs successfully, but I realize that the value stored in the collection variable is the value of the variable in the environment scope, instead of taking on the new value from the pre-request script.

Is this the way it should work?

What do I have to do to ensure that the value computed in the pre-request script is stored in the collection variable?

Hi there, using collectionVariables.set should set the collection variable, I just tried that and it worked (I had an environment variable with the same name which remained unchanged). Could you either include the relevant parts of your code or walk through what else is happening with the variables when your requests run? Am wondering if the variables are being set somewhere else too…

Here is my code:

    var seed = Math.floor(Math.random() * 899999999999 + 100000000000);
    var d = new Date();
    var sessionId = '{{source_bank_code}}' + d.getFullYear().toString().substr(-2)+("0"+(d.getMonth()+1)).slice(-2)+("0" + d.getDate()).slice(-2)+("0" + d.getHours()).slice(-2) + ("0" + d.getMinutes()).slice(-2)+("0" + d.getSeconds()).slice(-2) + seed;

    var ben_acc_num = "1234567892";


    pm.collectionVariables.set("session_id", sessionId);
    pm.collectionVariables.set("beneficiary_account_number", ben_acc_num);
    console.log(sessionId);
    pm.collectionVariables.set("name_enquiry_ref", sessionId);

Attached is images showing what transpires in the collection and environment variable
This is what we have in the collection variable before running the script:

This is what we have in the collection variable after running the script which is obviously different from the value in the script:


This shows that the value assigned to the variable is taken from the current value of the variable in the environment scope instead of the value in the script as confirmed in the response body

The amazing thing is that whenever I set the environment to “No environment”, the script executes well and assigns the right value to the collection variable. Also, if I change the name of the variable to a name different from that which exists in the environment variable, the script runs just fine as well.