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;
Related
Could someone tell me how to push elements into an array in localStorage?
My code:
(localStorage.getItem('projects') === null) ? localStorage.setItem('projects', ['proj1', 'proj2', 'proj3']) : '';
var ItemGet = localStorage.getItem('projects');
function CreateObject() {
console.log(ItemGet);
var Serializable = JSON.parse(ItemGet);
Serializable.push('proj4');
console.log(ItemGet);
}
<button onclick="CreateObject()">Add Object</button>
General approach:
let old_data = JSON.parse(localStorage.getItem('projects'))
let new_data = old_data.push(some_new_data)
localStorage.setItem('projects',JSON.stringify(new_data))
I would do the following assuming that your data is not a multiDimensional array.
(localStorage.getItem('projects') === null) ? localStorage.setItem('projects',
JSON.stringify(['proj1', 'proj2', 'proj3'])) : '';
var ItemGet = localStorage.getItem('projects');
function CreateObject() {
var Serializable = JSON.parse(ItemGet);
Serializable.push('proj4');
localStorage.setItem('projects',JSON.stringify(Serializable));
}
The problem you are hitting is that data stored in localStorage has to be a string. You'll have to parse/stringify before settting/getting anything from local storage. If you didn't want to work with strings, you may find something like IndexedDB API
const stuff = [ 1, 2, 3 ];
// Stringify it before setting it
localStorage.setItem('stuff', JSON.stringify(stuff));
// Parse it after getting it
JSON.parse(localStorage.getItem('stuff'));
Here is an example of using IndexedDB API from the docs
const dbName = "the_name";
var request = indexedDB.open(dbName, 2);
request.onerror = function(event) {
// Handle errors.
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create an objectStore to hold information about our customers. We're
// going to use "ssn" as our key path because it's guaranteed to be
// unique - or at least that's what I was told during the kickoff meeting.
var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
// Create an index to search customers by name. We may have duplicates
// so we can't use a unique index.
objectStore.createIndex("name", "name", { unique: false });
// Create an index to search customers by email. We want to ensure that
// no two customers have the same email, so use a unique index.
objectStore.createIndex("email", "email", { unique: true });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers");
customerData.forEach(function(customer) {
customerObjectStore.add(customer);
});
};
};
There are also other solutions out there like PouchDB depending on your needs
Say for example you have an array. This is how you can store it in the local storage.
let my_array = [1, 2, 3, 4];
localStorage.setItem('local_val', JSON.stringify(my_array))
Now to push any data into the local storage array you have to override by the new data like bellow
let oldArray = JSON.parse(localStorage.getItem('local_val'))
oldArray.push(1000)
localStorage.setItem('local_val', JSON.stringify(oldArray))
Requested URL sent - https://www.example.com/detail.guest.html?ppc=FDE466920006DCEFA697BF982FC9C87C5B257ECB2230CBF4D6D6CA740C7B894D5795F70DED928ED3B00C1F3F77DF974DFD73882DEBDD7EC063B37DEB24CF655528FD911109C57961AE314C612772AADFD2E193D572E6F6C8E249A6DAA
Get below response data correctly as expected by 3rd party.
BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2
I want to extract "BookersID", "BookersTitle", "BookersFirstName", "BookersLastName" separately and display this value in input field.
JS:
var bookerID = data[0].BookersID;
var bookerTitle = data[0].BookersTitle;
var bookerFname = data[0].BookersFirstName;
var bookerLname = data[0].BookersLastName;
console.log("BookersID", bookerID);
console.log("BookersTitle", bookerTitle);
But getting error in display value.
Please let me know how to get the value in console log?
Thanks
First you need to get data from your xhr request. To do that you need to add callback function. (More info in jQuery.get() documentation)
$.get( endpoint, function( data ) { // add callback to handle response
// ... parse data here
});
As I understand you need to parse data. It could be done by using String.prototype.split method and simple mapping.
console.log(data) // BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2
var parsed = data.split(';').map(part => ({ name: part.split('=')[0], value: part.split('=')[1] }));
console.log(parsed);
Output:
[
{name: "BookersID", value: "250100000002"},
{name: "BookersTitle", value: "Mr"},
{name: "BookersFirstName", value: "test1"},
{name: "BookersLastName", value: "test2"}
]
If you want to get data as an object:
var parsedObject = parsed.reduce(
(obj, item) => Object.assign(obj, {[item.name]: item.value}) ,{});
// {BookersID: "250100000002", BookersTitle: "Mr", BookersFirstName: "test1", BookersLastName: "test2"}
If you getting the same response you need to write a utility function to convert the same into an object
function _convert(responseString) {
var _obj = {};
responseString.split(";").forEach(function(pair){
var _pairArr = pair.split("=");
_obj[_pairArr[0]] = _pairArr[1];
});
reuturn _obj;
}
var responseString = "BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2";
var obj = _convert(responseString);
obj['BookersID']; // 250100000002
// or
obj.BookersID; // 250100000002
Note: This will only work if your response has exactly the same format as you have mentioned.
var str = 'BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2';
var data = {};
var parsed = str.split(';').map(part => { let x = part.split("="); data[x[0]] = x[1]; console.log(x) });
console.log(data)
Output:
{BookersID: "250100000002", BookersTitle: "Mr", BookersFirstName: "test1", BookersLastName: "test2"}
You could use .reduce() and .split() to create your string into an object, which can then have its properties accessed
const data = "BookersID=250100000002;BookersTitle=Mr;BookersFirstName=test1;BookersLastName=test2";
const dataObj = data.split(';').reduce((acc, kvp) =>
({
...acc,
...(([key, value]) => ({[key]: value}))(kvp.split('='))
}), {});
console.log(dataObj);
// access properties:
console.log(dataObj.BookersID);
I'm using firebase to make a chat application. I stumbled upon a little problem.
When making requests to the firebase database, firebase will return a JSON or JS object back (I'm new to this so I don't really know).
This is the structure of my database:
The first ID under the message tree is the client's ID which I get when a cidst connects to the application. The id's just below are the client'ID with whom the logged client chatted with and the Id below that is firebase generated ID for each message.
With this code (see below) I'm listening on the database to see if any messages have been added for notification purposes.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data) {
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs) {
if (msgs.hasOwnProperty(keys)) {
console.log(keys + " -> " + msgs[keys]);
messages.push(msgs[keys]);
}
}
}
The output of the code:
I'm getting an array with two objects. Until here everything works fine.
My problem is that I can't figure out how I can get my message properties from here using JavaScript since the Message-IDs are unknown.
What I mean is that I can't access the properties doing msgs[keys].id.message for example since ID is unknown.
var ref = database.ref('messages/81k44hlET5cq2AorxLDxD1DeXV52/');
ref.on('value', gotData, errData);
function gotData(data)
{
var msgs = data.val();
var keys = Object.keys(msgs);
console.log(msgs);
messages = new Array();
timestamp = new Array();
type = new Array();
for(var keys in msgs)
{
if (msgs.hasOwnProperty(keys)) {
console.log(keys , " -> " , msgs[keys]);
messages.push(msgs[keys]);
var k = msgs[keys];
for(var keys in k){
console.log( k[keys]);
}
//
}
}
You could iterate over your JavaScript object with the .forEach method, use Object.entries for this.
In the following code snippet, I am logging all message objects
const messages = {
kjzn5ef6ke2zlfzn: {
h6qjopdbgs5d6mv7f: {
gd73g4d5d9dvtjzj15: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
},
kdaz8bamd6kprmq78: {
message: "k",
seend: "true",
timestamp: "26/6/2018 20",
type: "send"
}
}
}
};
Object.entries(messages).forEach(([id1, a]) => {
Object.entries(a).forEach(([id11, b]) => {
Object.entries(b).forEach(([id111, message]) => {
console.log(id1, '=>', id11, '=>', id111, ':', message)
});
});
});
I am looking to get the the key from a firebase push command when using cloud functions.
const params = {
date: Date.now(),
movie,
movieId: movie.id,
userId: user.uid,
group: 'home',
type: 'watched'
};
const pastRef = event.data.adminRef.root.child(`pastActivity/${user.uid}`);
var newPostRef = pastRef.push().set(params);
var postId = newPostRef.key;
console.log(postId); //undefined
The postId however comes back as undefined. Have try a few other suggested methods without any results.
Reference.set() returns a void promise that resolves when the write operation completes. You can't get the key of it. Instead, split the push() and set(...) into separate statements, so that you can capture the reference
var newPostRef = pastRef.push();
newPostRef.set(params);
var postId = newPostRef.key;
console.log(postId); //undefined
A shorter version can be used if you don't need the newPostRef variable
//var newPostRef = pastRef.push().set(params);
//var postId = newPostRef.key;
const newPostRefKey = pastRef.push(params).key
//this pushes the data and returns the key
I have this code in my app.js for send chat and read chat in my application
$scope.messageshistory = {};
$scope.tmp = {};
// send message
$scope.sendMessage = function(){
$scope.messages = {
from : $scope.datauser['data']['_id'],
fromname : $scope.datauser['data']['nama'],
to : $scope.tmpuserid,
message : $scope.tmp['sendmessage'],
time : moment()
};
//event emit message
socket.emit('message',$scope.messages,function(callback){
if(!callback['error']){
$scope.messages['time'] = moment($scope.messages['time']).format('DD-MMMM-YYYY HH:MM');
if ($scope.messageshistory.hasOwnProperty($scope.tmpuserid)){ //yg di json yg paling awal
$scope.messageshistory[$scope.tmpuserid].push($scope.messages);
}else{
$scope.messageshistory[$scope.tmpuserid] = [];
$scope.messageshistory[$scope.tmpuserid].push($scope.messages);
}
$scope.tmp['sendmessage'] = '';
}else{
var msg = callback['error'];
navigator.notification.alert(msg,'','Error Report', 'Ok');
}
$scope.$apply();
});
};
//event read message
socket.on('message', function (data) {
window.plugin.notification.local.add({
id : moment(),
title : data['fromname'],
message : data['message'].substr(0,20) + ' ...',
led : 'A0FF05',
json : JSON.stringify({ routes:'chat', nama :data['fromname'],from:data['from'] })
});
data['time'] = moment(data['time']).format('DD-MMMM-YYYY HH:MM');
if ($scope.messageshistory.hasOwnProperty(data['from'])){
$scope.messageshistory[data['from']].push(data);
}else{
$scope.messageshistory[data['from']] = [];
$scope.messageshistory[data['from']].push(data);
}
for(var i = 0; i<= $scope.datauser['data']['friends'].length; i++){
if($scope.datauser['data']['friends'][i]['userid'] == data['from']){
$scope.datauser['data']['friends'][i]['ischat'] = true;
break;
}
};
$scope.$apply();
});
my question is how to take the last value in message property from $scope.messageshistory, because $scope.messages is for sending the message and $scope.messageshistory is to keep the chat history. This is the chat activity image:
just from this activity, $scope.messageshistory will save the data in it JSON as:
{
"5512": [{
"from": "561c",
"fromname": "ryan",
"to": "5512",
"message": "hey",
"time": "18-Maret-2016 21:03"
}, {
"from": "5512",
"fromname": "sasa",
"to": "561c",
"message": "hello",
"time": "18-Maret-2016 21:03",
"_id": "593s"
}]
}
I get this value from using angular.toJson($scope.messageshistory), and this array will always add up if the chat activities still going on. And my intention to get the last value in message property from $scope.messageshistoryis to use in Text-to-Speech feature in my application. This is the code:
$scope.speakText = function() {
TTS.speak({
text: **this the place for the code**,
locale: 'en-GB',
rate: 0.75
}, function () {
// handle the success case
}, function (reason) {
// Handle the error case
});
};
it will read the last message in $scope.messageshistory. So, what code that I must write to take the last value?
You have to do the following:
var msgs = $scope.messageshistory[$scope.tmpuserid]
var yourLastMessage = msgs[msgs.length-1].message
// you could also add a quick check so you don't get
// an error if the messages array is emtpy :
// var yourLastMessage = (msgs && msgs[msgs.length-1] ? msgs[msgs.length-1].message : null)
Edit
Some explanation per your comment :
var msgs = $scope.messageshistory[$scope.tmpuserid]
// msgs is now an Array containing Objects
// [{message : 'xxx'},{message : 'yyy'}]
// we take the last entry of the msgs Array (msgs.length-1)
// so msgs[msgs.length-1] is the last object ({message : 'yyy'})
// and finally we take the 'message' property' of that object:
var yourLastMessage = msgs[msgs.length-1].message
assuming that the keys in the history object are ascending numbers and taking into account that the order of keys in an object is not specified by W3C you will have to do the following:
get all keys
find the "latest" (hence the biggest number)
fetch it
so you could do for example
var keys = Object.keys($scope.messagehistory);
keys.sort (function (a, b) {
return a - b;
});
var result = keys[keys.length - 1];