Cannot create property '_id' on string

Hello,

I want to fill a database with random numbers using MongoDB. There are 3 nodes, 1 timestamp, 1 function where the random numbers are created and returned as a msg, 1 collection node of MongoDB. I have adjusted my MongoDB settings but the problem seems to exist in the function node. There is a type error "can not create property '_id' on string" in which I am not using the id right.

-All nodes are connected with each other.

Thanks for your time, appreciate your help.

msg.payload is a number, i.e a timestamp.
It is not an object so you can not add properies to it.
Either set it as a object i.e msg.payload = {}; you would need to move the timestamp to another var first i.e var hold = msg.payload; or it will be overwritten
Then you can do
msg.payload._id = 1234;

or

you can do it in one go
msg.payload = {_id:1234,timestamp: msg.payload};`
which will make msg.payload an object with the properties _id and timestamp.

Thanks for your reply, I am a beginner with Node-Red and I tried to implement your second solution but I still get this error. Can you please help me again? Thank you!

MicrosoftTeams-image

MicrosoftTeams-image (1)

Data generation code:
msg.payload=(Math.round(Math.random()*1000))/100;
msg.payload = {​​​​​​​_id:1234,timestamp: msg.payload}​​​​​​​;
return [msg];

The error is from your collection node, it is probably looking for msg._id
Try

​​​​​​​​​​​​​​msg.payload=(Math.round(Math.random()*1000))/100;
msg._id = msg.payload;
return msg;

I would think though that the input is msg.payload, what is the collection node and where is the help info/readme

image

I tried it but I still get the same error on MongoDB. I have attached an image of the MongoDB settings. Thanks for your help, I really appreciate it.

you need to select msg.payload in the settings
and the function should return an object. you do not need to set msg.id unless you are over writing an existing entry.
try

​​​​​​​​​​​​​​msg.payload={payload: (Math.round(Math.random()*1000))/100};
return msg;

Thanks a lot !

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