I will look into that but I am sure, that will make it even more complicated.
At this point I thought I will just do it with the $function accumulator to bypass all the jibjab and do it that way. Now I surprisingly found out, that despite the mongo Compass passing the aggregation, actually using the aggregation from my nestjs application does not work.
This seems rather counterintuitive.
let insert = await this.testSchema.insertMany([{
ProjId: 12,
ArtifactAttributes: [
{
_t: "ArtifactAttributes",
AttrId: 1,
AttributeName: "Description",
AttributeValue: "Test Description"
},
{
_t: "ArtifactAttributes",
AttrId: 2,
AttributeName: "Details",
AttributeValue: "Test Details"
}
]
}])
let toBeInserted = {
"_t": "ArtifactAttributes",
"AttrId": 0,
"AttributeName": "Owner",
"AttributeValue": "Test Owner"
}
await this.testSchema.aggregate([{
$set: {
"ArtifactAttributes": {
"$function": {
body: function (obj, inserter) {
obj.sort((a, b) => b.AttrId - a.AttrId)
inserter["AttrId"] = obj[0].AttrId + 1
obj.push(inserter)
return obj
},
args: ["$ArtifactAttributes", {
"_t": "ArtifactAttributes",
"AttrId": 1,
"AttributeName": "Owner",
"AttributeValue": "Test Owner"
}],
lang: "js"
}
}
}
}])
This is exactly the aggregation from mongoCompass:
But calling that function RETURNS the updated document, but does not apply it in the database…
{
"_id": {
"$oid": "61b7819a86c901a8cc159b0a"
},
"ArtifactAttributes": [{
"_t": "ArtifactAttributes",
"AttrId": 1,
"AttributeName": "Description",
"AttributeValue": "Test Description"
}, {
"_t": "ArtifactAttributes",
"AttrId": 2,
"AttributeName": "Details",
"AttributeValue": "Test Details"
}],
"ProjId": 12,
"__v": 0
}
But console logging the request gives me the new object:
{
"_id": "61b780cebc97c5e07b523b44",
"ArtifactAttributes": [
{
"_t": "ArtifactAttributes",
"AttrId": 2,
"AttributeName": "Details",
"AttributeValue": "Test Details"
},
{
"_t": "ArtifactAttributes",
"AttrId": 1,
"AttributeName": "Description",
"AttributeValue": "Test Description"
},
{
"_t": "ArtifactAttributes",
"AttrId": 3,
"AttributeName": "Owner",
"AttributeValue": "Test Owner"
}
],
"ProjId": 12,
"__v": 0
}