I have a large script, the following section is the relevant part, but if people prefer I can post the whole script on request.
The script iterates through a list, looking for a field called colour
and renames it color
.
{
serviceAgreementRefList: {
$map : {
input: "$$this.relatedJson.serviceAgreementRefList",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{
$ne: [
"$$this.situation",
undefined
]
},
"situation": {
$mergeObjects: [
"$$this.situation",
{
color: "$$this.situation.colour",
}
]
}
},
{},
]
}
]
}
}
}
}
It works as expected for the most part, however, if the object situation
exists but is null
then the script creates an empty situation
object.
I would like any null situation
objects to remain null.
How can I achieve that?
I thought I could add an $or
function to the $cond
, but of course that doesn’t worse and in fact makes the problem worse.
Can I use an $in
function, containing two $ne
functions, one for undefined
and one for null
?
I would imagine I can, but I can’t get the syntax right.
2
Answers
So the solution here is to use the
$eq
function instead of$ne
and compare the type of the field to what we're expecting it to be.If the type matches what we expect then the field name will be modified, if it doesn't, then nothing will be changed.
this is what the
$cond
function should look like:if
situation
is populated then$type
will return"object"
, if it isnull
then$type
will return"null"
and if it does not exist$type
will return"missing"
.In Node, using Mongoose I solved it using this.
Define a default value in the object/array definition in yous schema
default:()=> undefined
This will ignore the object or array when it comes empty in your object. It will just not create it instead of creating an object with null values
For example, within a field called "operation" definition which is an array, I defined the element like this.