MongoDB update (mongodb3)

Hi all,
I am learning to use MongoDB to store data, and now I am having an issue with the "update" method. I am using the nodes from "node-red-contrib-mongodb3".

I have inserted some documents, which have some static data (descriptive information of what is stored in the document) and dynamic values, which represent the actual status of the variables.

So, I am using the funcion "update", and I pass the msg.payload containing an array, in which the first position selects the identifier of the document (I don't use "_id", but another static value), and the second position of the array contain the dynamic values that must be updated.
The document is something like that.

{
   "_id":123456
   "timestamp": 0,
  "tag": "ABCD",
  "type": "read",
  "units": "ÂşC",
  "freq": 12,
  "value": 0,
  }

Here, "value" and "timestamp" are the dynamic values that are updated. And I use "tag" as identifier.

So, the payload that I am passing to the "mongdb3 in" node, which the operator "update" is:

msg.payload= [{"tag": "ABCD"} ,{"value":msg.payload, "timestamp": new Date()}];

The result is that, in the document containing "tag": "ABCD", not only the fields "value" and "timestamp" are updated, but the other fields of the document are removed. So that the document becomes like that:

{  "_id":123456, 
  "value": 55.9,  
  "timestamp": {    "$date": {      "$numberLong": "1657534300702"    }  }
}

How can I avoid it to happen?

Thanks in advance.

Hi,
I reply myself because I found the error. I just forget using the operator "$set" :man_facepalming:

msg.payload= [{"tag": "ABCD"} ,{"$set":{"value":msg.payload, "timestamp": new Date()}}];

Now it works as expected.

Best regards!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.