I have a seemingly straight forward query to update the names of like objects in a mongo doc. But it fails as not all docs have comment.. what should i be looking for in the docs get around this and update only the docs that have likes on comments?
return this.model.updateMany(
{
comments: {
$exists: true
}
},
{
$set: {
'comments.likes.$[like].actor.firstName': user.firstName,
'comments.likes.$[like].actor.lastName': user.lastName,
},
},
{
multi: true,
arrayFilters: [
{ 'like.actor.username': user.username },
],
},
);
The problem is that not all comments are liked.. so then the query complains:
WriteError: The path 'comments.likes' must exist in the document in order to apply array updates.
Full output:
WriteError: The path 'comments.likes' must exist in the document in order to apply array updates.
Details:
WriteError({
"index" : 0,
"code" : 2,
"errmsg" : "The path 'comments.likes' must exist in the document in order to apply array updates.",
"op" : {
"q" : {
"comments" : {
"$exists" : true
}
},
"u" : {
"$set" : {
"comments.likes.$[like].actor.firstName" : "GGGJOHN",
"comments.likes.$[like].actor.lastName" : "Carmichael"
}
},
"multi" : true,
"upsert" : false,
"arrayFilters" : [
{
"like.actor.username" : "john.carmichael"
}
]
}
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.updateMany@src/mongo/shell/crud_api.js:655:17
@(shell):1:1
Here is an illustration of the doc in q, where comments is an array and the likes on a single comment is also an array: