Home > Mobile >  MongoDB if statement in a parameter
MongoDB if statement in a parameter

Time:11-04

I am trying to not make my code redundant and I would like to know, if in a .updateOne method, when Im passing data to change, if its possible to implement if statement to choose from the data. Here is a situation.

I have my db model:

const depositarySchema = new Schema({
    euid: {
        type: String,
        required: true
    },
    euid2: {
        type: String
    },
    count: {
        type: Number,
        required: true
    },
    euroPallets: {
        type: Number,
    },
    biggerPallets: {
        type: Number,
    },
    otherPallets: {
        type: Number,
    },
    depositary: {
        type: Number,
        required: true
    },
    title: {
        type: String
    }

}); 

Then I have a variable: var = 1 for euroPallets, 2 for biggerPallets and 3 for otherPallets. I would like to implement something like this:

Depositary.updateOne(
  {
   euid: euid,
  },
  { 
   count: dep.count - palletCounter,
   if(var === 1){
    euroPallets: count}
   elseif(var===2){
    biggerPallets: count}
   else{
    otherPallets: count} 

},

where count is just a number. I hope its understandable what im trying to achieve, sorry for a wrong syntax.

CodePudding user response:

Maybe this one:

let upd = { 
   euid: euid,
   count: dep.count - palletCounter
};

if (var === 1) {
   upd['euroPallets'] = count;
}
else if (var === 2) {
   upd['biggerPallets'] = count;
}
else {
   upd['otherPallets'] = count;
}

Depositary.updateOne(upd)

EDIT:

For .updateOne() method to actually work like I want to, you need to separate the euid parameter. The correct solution is this:

let upd = { 
       count: dep.count - palletCounter
    };

    if (var === 1) {
       upd['euroPallets'] = count;
    }
    else if (var === 2) {
       upd['biggerPallets'] = count;
    }
    else {
       upd['otherPallets'] = count;
    }


 Depositary.updateOne(
  {
   euid: euid,
  },
upd,
)

CodePudding user response:

Wernfried Domscheit beat me to it, but I will post my answer anyways.

const palletTypes = ['otherPallets', 'euroPallets', 'biggerPallets'];
var count = ep.count - palletCounter;
var palletType = palletTypes[count] || palletTypes[0];

var pallets = {'count': count};
pallets[palletType] = count;

Depositary.updateOne(
    {euid: euid},
    pallets
)

I would honestly just make a helper method so you can just send in parameters and it will turn everything to the correct objects.

updatePallets(euid, ep.count, palletCounter)
  • Related