How do I access neo4j result properties? - javascript

I have a neo4j query in JavaScript that return two sets of nodes:
session
.run ("MATCH (user:Dealer)-[:SUPPLY]->(v) RETURN user,v")
.then (function(result)
{
if ( !result.records[0])
---no records
else {
email=result.records[0].properties.email; //this doesn't work
}
I want to access the properties from both user and v in a nested for loop so I need direct access to each property field. The developers manual tries to explain it but not very well.

The Result returns you a collection of records.
A Record can be compared to a row in the neo4j browser and has a simple get method for accessing record values, in your use case, for having the user :
user = result.records[0].get('user');
When you expect a node or a relationship to be returned, they contain a properties object which represent key value pairs of properties.
A node has also a labels property representing the labels of a node
email = user.properties['email'];
labels = user.labels; // returns the node labels

Related

How can I use variables in an update operation in mongodb that involves an array or another type of embedded or nested document?

The document in the target collection ("myCollection") has a field called "japanese2". This is an array (or an object) that contains an object that contains a property called "japanese2a". The value of this property is initially set to 0 (although it may change later). I want to change this value to 100 with a script in node.js (I am using the Express framework). The database is Mongodb, the free cloud version called Atlas.
If I do this without using variables, it works well:
db
.collection("myCollection")
.updateOne({username:username}, {"$set":{"japanese2.0.japanese2a":100}});
However, if I try this using variables for both the field name, "japanese2", and the name of the element/property in the array/object, "japanese2a", it fails. I have tried the below and other variations but I couldn't find a solution. I have researched stackoverflow for an answer but couldn't find a solution.
There is only one element/property in the array/object to start with.
var field = req.body.fieldName; //want to set this for the field name="japanese2"
var task = req.body.question; //want to set this for the name of the element="japanese2a"
var myField = [task];
field = myField;
var fieldPos = field[0];
.
.
.
db
.collection("myCollection")
.updateOne({username:username}, {"$set":{[fieldPos]:100}});
The above creates a new field called "japanese2a":100" but it does not appear in the array under the field called "japanese2", which is what I want.
I don't get any error messages when I do the above in the console (probably mostly due to the fact that I haven't put in error statements/functions to catch errors), but the output is not correct.
Another way of updating that I found from here:
https://www.codementor.io/#prasadsaya/working-with-arrays-in-mongodb-16s303gkd3
that involves using something like this:
db.posts.updateOne(
{ _id : ObjectId("5ec55af811ac5e2e2aafb2b9"), "comments.user": "Database Rebel" },
{ $set: { "comments.$.text": NEW_CONTENT } }
)
doesn't work for me, as I don't know if the initial value of the element in the array will always be a zero or some other constant. And there is only one element in the array initially. I can only use the username for the match part in the updating. I can't make an expression that is a perfect match for some element in the array.
The update solution from here: MongoDB update data in nested field
db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} });
works, and that is what I used successfully to update in the first updating attempt above, but I don't know how to incorporate variables into the updating operation, specifically a variable for the field name ("japanese2") that holds the array or the object, and the name of the first and only element/property in the array/object ("japanese2a").
EDITED: I asked for a solution for an "array" originally, but either a field that acts an array (that holds elements that act as objects) or an object (that holds other objects as properties) works in my case, so I edited the question body and title. Also, the accepted solution works with the field as an entity that holds an array, or as an entity that contains an object inside it.
In either case, if there is already a field with the appropriate name, an object is created (if it didn't already exist) as an object of that object called "field" or the array called "field", and the object's property is set as according to the variables in the script.
If the field doesn't exist, it's created (as an object), and this object contains another object that contains the property ("task" as the name and "100" as the value for the name-value pair). So the newly created "field" object contains an object as its property. The property of this object is a name-value pair of "japanese2a" and "100".
If the script is run again, with a different "task" name (eg. "japanese2b"), another property is created, with the name of "japanese2b" and the value of "100". It is created within that same object that is "inside" the "field" object, so the object field.0 (the object within the "field" object) ends up looking like this: {japanese2a: 100, japanese2b: 100}. And the object called "field" looks like this: {{japanese2a: 100, japanese2b: 100}}.
I think something like
var field = req.body.fieldName // japanese2
var task = req.body.question; // japanese2a
var updateObj = { $set : {} };
updateObj.$set[field + '.0.' + task] = 100
db
.collection("myCollection")
.updateOne({username:username}, updateObj);
Might work

What is the output type of cts.uris in MarkLogic?

I'm using cts.uris in my search query. I'm assigning it to a variable like:
var x = cts.uris(...);
What is the output type of x?
I'm using JSON documents in my application and want to use xdmp.nodeReplace on some 2 objects. I'm performing an update on my document after checking the value of "x" to be valid or not after writing a search query inside cts.uris.
if(x.toString().length>0)
//x is cts.uris output. Checking if it gets a value then do the update like this.
{
var newObject = x;
newObject.field1="new value";
//field 1 value updated in the clone of original file
newObject.field2="new value"; //same as above
return xdmp.nodeReplace(x, newobj);
}
I expect the newObject to have all the contents of the origial file that we fetch and put in "x" and then update the values as given in the above code.
Once it is updated then it should replace the original document with the new values.
I'm currently getting an error like: "XDMP-ARGTYPE: xdmp.nodeReplace"
cts.uris returns a Sequence of uris. You probably want to iterate over the Sequence using a JavaScript for..of construct. An example is given in above link.
Note though that a uri is not a full document, but just its identifier. It doesn't make sense to assign values to it like that.
To make updates to documents inside MarkLogic, either reinsert the document, or read it using cts.doc, isolate the property you want to update, and nodeReplace it as you intended.
HTH!

Javascript create 2d Array with ids as array key

I need an array structure that includes the user id as array key and can store more information about that user (2 dimensional array). In my case if he is allowed to perform database requests, these are represented by request id and true/false.
Each user can have multiple requests
For example:
User id =14 and requests ids =22 and true and 45 and false
User id =12 and requests ids =44 and false and 77 and false
It should look like this:
var users_rights={14:{22:true,45:false},12:{44:false,77:false}}
I’m struggling with js syntax since
var id[14] ;
Creates an array with 14 elements and the rest of the array is empty but I want an array where at the 14 position all my requests information are stored.
You can use the [] syntax with regular JS objects like the one you describe. Simple example:
var ob = {10: {11:true}, 12: {13: false}};
console.log(ob[10]); //Displays the object {11:true}
console.log(ob[10][11]); //Displays true
If you create the array first, then assign the values you will edit only the nth element e.g.
var id = [];
id[14] = 'xyz'
Gives an array with 14 undefined's and 'xyz' as the 15th element.
It sounds as though you don't want an array at all, you want an object with object values for its properties (or if you're using ES2015, a Map of Maps).
Your
var users_rights={14:{22:true,45:false},12:{44:false,77:false}}
(which is perfectly valid syntax, other than you should have a ; at the end) gives you the former: You index into it with the user ID (14) and then index into the object you get as a result with the request IDs (22 and/or 45), which gives you a boolean value.
You create an object like this:
var users_rights = {};
You add a property to it for the key 14 like this:
users_rights[14] = {};
You add properties to that the same way:
users_rights[14][22] = true;
users_rights[14][45] = false;
These objects are just plain objects, not arrays. Brackets notation works with them just fine (in fact, it's the fact that brackets notation works with objects that makes it work with arrays, because standard arrays in JavaScript aren't really arrays at all).

map relationship between object in javascript

I am using meteor for development which using mongo db as store. Thats means that all operations are just display object value (frontend) or operate object (backend). For example, from [user] collection "copy" value (userId) to [message] collection but different key name. is there any way better to
describe the relationship between two object rather than using
message.userId = user._id
maybe using a object to describe
{"userId","_id"}
There are many ways to skin a cat. This is how I would do it.
I would first create a mapping object with key-value pairs which represent the field relations between the two objects. The keys are the keys from the first object and the values are the keys from the second object.
{
"userId":"_id",
"userName":"name"
//...
}
Then I would use a function like this to apply the mapping object to two objects:
function applyMapping(fromObj, toObj, mappingObj) {
for (fromKey in mappingObj) {
var toKey = mappingObj[fromKey];
toObj[toKey] = fromObj[fromKey];
}
}

Accessing Nested Objects in Json

I have a custom object which contains other items (ie arrays, strings, other types of objects).
I am not sure how to traverse the object to iterate and list all of the object types, keys, and values of the nested items.
Second to this issue I don't know how many levels of nesting there are (as the object is generated dynamically from the back-end and passed to me as one object).
Any ideas (and should I just use javascript/jQuery or both to do this most efficiently)?
Thanks I'll give the code a go. I am retrieving a result set from a webservice which returns a different set of columns (of differing datatypes) and rows each time. I don't know the names of the columns which is why I am trying to get the data however I can.
Depending on the datatype I will perform a different action (sum the amount, format it etc).
JSON-serialized objects contain a hierarchy, w/o any reference cycles, so it should be fairly straightforward to traverse, something like
function visit(JSONobj, f)
{
for (var key in JSONobj)
{
var value = JSONobj[key];
f(key,value);
if (value instanceof Object)
visit(value, f);
}
}
where f is a function that does something with keys and values. (of course you could just write a function to do this directly).
What exactly are you trying to find within the object?

Categories