简体   繁体   中英

MongoDB Node-Red Update

I want to update data in my MongoDB with Node-Red using mongodb3 node.

This is my function before the mongo node:

var payload = msg.payload;
var newMsg = {payload: {}};

var doc = {
    $set:{
        temp:23,
        hum:99
    }
};

newMsg.payload.selector= {address: payload.address};
newMsg.payload.document = doc;
newMsg.payload.options = {upsert: true};

return newMsg;

I got this error:

UnhandledPromiseRejectionWarning: MongoError: document must be a valid JavaScript object.

Anyone knows what to do?

Try the following:

    var newMsg = msg;
    newMsg.collection = '<insert your collection name>';
    newMsg.operation = 'update';
    newMsg.payload = { 
       {},
       $set:{
          "temp":23,
          "hum":99
       }
    };

    return newMsg;

The mongodb3 documents says about msg.payload -

  • To pass a single parameter to an operation use msg.payload as your parameter (eg {_id: 1243}).

  • To pass multiple parameters to an operation fill msg.payload with an array.

  • If you want to pass a single parameter WHICH IS AN ARRAY (eg as with InserMany), wrap your array in an outer array: msg.payload = [[{_id: 1243}, {_id: 2345}]]

msg.payload is actually parameters to a operation method ('insert', 'update',...). You can find document for parameters for all the methods here

In your case:

var newMsg = msg;
newMsg.collection = 'collection-name';
newMsg.operation = 'update';
newMsg.payload = [
  {}, // filter
  { // update
    "$set": {
      "field to be updated": "value to be updated",
      ...
    }
  },
  {} // options [optional]
  function() {} // callback [optinal]
];

return newMsg;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM