0

I have an object "input" and will be passed to query like a parameter:

var input = {
    id: 1,
    componentId: x,
    commands: [...],
    user: [...],
}

And the collection "testCollection":

testCollection = {
    id: 1,
    model: {
        stepComponents: [
           {  
            componentId: x
            command: [...],
            user: [...],
           }
         ]
    }
}

My question is how can I update a specific field on "testCollection" and skip the update if it is undefined or null. That means if "input.user" is undefined/null, then not update "user" field.

The update query sample is below:

testCollection.update(
  {
    _id: objectId(input.id),
    'model.stepComponents.componentId': input.componentId
  },
  {
    'inputs': input.inputs,
    'model.stepComponents.$.commands': input.commands,
    'model.stepComponents.$.users': input.users,
  },
  { upsert: true },
);

Any help would be appreciated. Thanks.

3 Answers 3

2

I was struck at the same problem and solved by below solution

  let params= {
      id: req.body.id, componentId: req.body.x, commands: req.body...,
  }

  ;
  for(let prop in params) if(!params[prop]) delete params[prop];//it will remove fields who are undefined or null 

  testCollection.findOneAndUpdate( {
      _id: req.params.id
  }

  , params);
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for my late response, it solved my problem, thank you.
2

Try this one:

testCollection.update(
{
  _id: objectId(input.id),
  user: {$ne: null}
},
{
    $set: {input}
}

);

1 Comment

It's not suitable for my case, anw, thanks for your help :)
2

You can try to use exists

db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.