Require a JSON file in Node.js Then Access/Iterate Through It? - javascript

I believe the error here lies in how I have my Json structured, but this is what is happening.
I have a Json file that looks something like this (omitting key values to protect information):
{
"services" : [
{
"server" : "info",
"baseURL" : "http://info.info.net",
"controlPanelURL" : "http://infoadmin.info.net",
"paths" : {
"restaurantManagerPath" : "/info",
"transactionManagerPath" : "/info",
"userManagerPath" : "/info",
"recordHistoryPath" : "/info"
}
},
{
"server" : "info",
"baseURL" : "http://info.info.net",
"controlPanelURL" : "http://infoadmin.info.net",
"paths" : {
"restaurantManagerPath" : "/info",
"transactionManagerPath" : "/info",
"userManagerPath" : "/info",
"recordHistoryPath" : "/info"
}
}
]
}
I require this file in my main app.js entry-point like so:
const Data = require("./data.json");
Now, if I console.log(Data), I will be shown this:
Now for my problem. It seems I cannot "access" this as an object even though I know using require() on a Json file automatically parses it. Nor can I loop through it with a for...in loop. Here are some examples. Please ignore the "this.json" file, it is a copy of the actual "data.json" file.
Any info would be much appreciated. Thank you in advance for you input on my probably dumb question.

Related

Mongo script to update an object if its a certain value

I am trying to update a document in Mongo if it has a certain value within a field.
{
"_id" : ObjectId("myObject"),
"source" : "BW",
"sourceTableName" : "myTable",
"tableName" : "tier",
"type" : "main",
"fieldMappings" : [
{
"sourceField" : "tier_id", <~~~~ If this is "tier_id", I want to change it to "trmls_id"
"reportingField" : "bw_id",
"type" : "integer",
"defaultMap" : {
"shouldErrorOnConvert" : false
}
}
]
}
I tried something like
db.getCollection('entityMap').update({"sourceTableName":"myTable"}, {"fieldMappings.0.sourceField":"trmls_id":{$exists : true}}, { $set: { "fieldMappings.0.sourceField": "tier_id" } })
and I think it is failing on the $exists parameter I am setting.
Is there a more cleaner/dynamic way to do this?
The whole query I am trying to formulate is
In the table myTable
I want to check if there is a sourceField that has the value tier_id
If there is tier_id, then change it to trmls_id
Otherwise do nothing
If there is a similar StackOverflow question that answers this, I am happy to explore it! Thanks!
There is a syntax mistake and you can use positional operator $ in update part because you have already selector field in query part,
db.getCollection('entityMap').update(
{
"sourceTableName": "myTable",
"fieldMappings.sourceField": "tier_id" // if this field found then it will go to update part
},
{
$set: {
"fieldMappings.$.sourceField": "trmls_id"
}
}
)

Store a dataURL in MongoDB to access it via local URL (JS)

So I don't know if my title is clear enough, what I want to do is, in my Meteor App, to have a tool that upload a file into my MongoDB, and output an URL that I could use it for example to display as the src of an
Yet, I create my Collection:
export const Files = new Mongo.Collection('files');
and a addFile function :
export const addFile = (nameArg: String, dataURL: String) => {
Files.insert({
_id: uuid(),
name: nameArg,
url: dataURL
});
console.log("file "+nameArg+" added");
};
Then I use the react-jsonschema-form package to display a file form
<Form
schema={{
type: 'object',
properties: {
file: {
type: 'string',
title: 'Upload an image to get its URI'
}
}
}}
uiSchema={{
file: {
'ui:widget': 'file'
}
}}
onChange={this.onChange}
liveValidate
>
<div />
</Form>
My onChange function :
onChange = (e: { formData: { file: string } }) =>{
const [dataType, nameBis,] = e.formData.file.split(';');
const name = nameBis.split('=')[1];
Promise.resolve().then(addFile(name, e.formData.file));
}
And I'd like to use an address sush as window.location.host+'/file/'+name
to be able to use this image.
I believe it to be possible, but how ?
Thanks for all responses :)
This is very much possible and in a secure way using packages cfs:standard-packages and cfs:filesystem. Frankly speaking, I did not go in depth for your question.
It is a beautiful package. You can read about above here packages in depth.
CODE TO CREATE FILESYSTEM COLLECTION
var imageStore = new FS.Store.FileSystem("YOUR_COLLECTION_NAME");
YOUR_COLLECTION_NAME = new FS.Collection("YOUR_COLLECTION_NAME", {
stores: [imageStore]
});
In Short. The files will be saved at the sibling to bundle/ location at cfs/files/YOUR_COLLECTION_NAME. Information about the file will be saved in the collection cfs.YOUR_COLLECTION_NAME.filerecord and temporary location will be used for internal purpose with collection cfs._tempstore.chunks as below.
If you save any file using above package. The metadata will be saved inside the cfs.YOUR_COLLECTION_NAME.filerecord as below
{
"_id" : "TBmxbsL2cMCM2tEc7",
"original" : {
"name" : "photo.jpg",
"updatedAt" : ISODate("2017-07-06T12:54:50.115Z"),
"size" : 2261,
"type" : "image/jpeg"
},
"uploadedAt" : ISODate("2017-07-08T06:58:32.433Z"),
"copies" : {
"YOUR_COLLECTION_NAME" : {
"name" : "photo.jpg",
"type" : "image/jpeg",
"size" : 2261,
"key" : "YOUR_COLLECTION_NAME-TBmxbsL2cMCM2tEc7-photo.jpg",
"updatedAt" : ISODate("2017-07-08T06:58:32.475Z"),
"createdAt" : ISODate("2017-07-08T06:58:32.475Z")
}
}
}
at Client side, you can get the link to the document file using
YOUR_COLLECTION_NAME.find({"_id" : "TBmxbsL2cMCM2tEc7"}).url();
This url is token based safe link to the file instead of direct location to your server. You can set additional allow/deny settings for download ans stuff just like normal collections. Hope this helps!

protobuf.js translate proto file to JSON descriptor, repeated gets lost

I'm using Protobuf.js to build a node package, containing our protocol and offering encode and decode functionality to Proto Messages defined in this package. I would be fine with using .proto files (The loading of .proto files happens at runtime) , but since the module needs to be usable on the client side and I can't pack the .proto files to my resolved .js-file (built with browserify), I need to use a way, that enables the packaging in the build.js.
Enter JSON Descriptors.
var jsonDescriptor = require("./awesome.json"); // exemplary for node
var root = protobuf.Root.fromJSON(jsonDescriptor);
The json file can be packed up (requirement resolved by browserify). Proto Type Defintions also are possible in .json
I translated my .proto file into a .json file and tried it with my example data. Unfortunately it failed with the repeated fields.
The .proto file looks kind of like this:
message Structure {
map <int32, InnerArray> blocks = 1;
}
message Inner{
int32 a = 1;
int32 b = 2;
bool c = 3;
}
message InnerArray{
repeated Inner inners = 1;
}
Which I translated into this JSON Descriptor
{
"nested": {
"Structure": {
"fields": {
"blocks": {
"type": "InnerArray",
"id": 1,
"map" : true,
"keyType" : "int32"
}
}
},
"InnerArray" : {
"fields": {
"inners" : {
"repeated" : true,
"type" : "Inner",
"id" : 1
}
}
},
"Inner" : {
"fields" : {
"a" : {
"type" : "int32",
"id" : 1
},
"b" : {
"type" : "int32",
"id" : 2
},
"c" : {
"type" : "bool",
"id" : 3
}
}
}
}
}
If I'm not mistaken there is the required attribute for a field.
When I encode and decode my example data it stops at the repeated field: (note that the map works fine).
{
"blocks": {
"0": {
"inners": {}
},
...
I also examined my root to find out how the loaded type looks and it looks exactly like my defintion EXCEPT that repeated is missing:
"InnerArray" : {
"fields": {
"inners" : {
"type" : "Inner",
"id" : 1
}
}
},
How do I define a repeated field correctly in a JSON Descriptor?
If there is a way to pre include proto files and not load them at runtime, so that i can wrap them up with browserify, I would accept this as a solution, too.
After browsing through the code, I found that you can not set required in a JSON Descriptor.
The correct way is to set
"rule": "repeated";
since a field is set with a Field Descriptor

MongoDB - Updated $ref value unable to query new value

I've posted the following question which has been answered correctly:
MongoDB - Updating only $ref from DBRef field type
Despite of this when I execute the find method like this:
{ "codeId" : { "$ref" : "code" , "$id" : { "$oid" :
"4ff1c08c6ef25616ce21c4b6"}} }
The document isn't returned... Any idea why?
After the update the document is stored like this:
{ "_id" : { "$oid" : "5097ae1cd3159eb52d05574c"} , "codeId" : { "$ref"
: "code" , "$id" : { "$oid" : "4ff1c08c6ef25616ce21c4b6"}} }
By the way, using uMongo GUI, if I select the Update option over this stored document, and save it, without making any changes whatsoever, and then make the find query once again, the document is returned by the query...
Thanks
This is a clearly one of those DBRef "tweaky" things...
As a temporary (but probably correct) fix, I managed to solve this problem executing this javascript procedure:
var cursor = db.menu.find( { "codeId.$ref" : "version" } );
while( cursor.hasNext() )
{
var document = cursor.next();
db.menu.update(
document,
{ $set: {"codeId" : DBRef("code", document.codeId.$id) }},
{ upsert: false, multi: true }
);
}
Still, I won't consider this to be the best way to achieve what I want... Any other solution that involves less lines?

JsTree multitree cookie

Hello guys I use jstree and I have multiple tree in the same page. I have two problems:
1) I want cookies in order to distinguish which nodes are open in each tree. I try to implement this functionality using prefix but unfortunately:
"cookies" : { "cookie_options" : { "prefix" : "home" } },
does not work since only the last opened node is re-opened after refresh.
2) I do not want to be able to create new root nodes.I only want to be able to create files or transfer files into my root directory.
I am trying to achieve that using:
"types" : {
"types" : {
// The default type
"default" : {
"valid_children" : "none",
"icon" : {
"image" : "./file.png"
}
},
// The `folder` type
"folder" : {
"valid_children" : [ "default", "folder", "file" ],
"icon" : {
"image" : "./folder.png"
}
},
// The `drive` nodes
"drive" : {
// can have files and folders inside, but NOT other `drive` nodes
"valid_children" : [ "default", "folder" ],
"icon" : {
"image" : "./root.png"
},
// those prevent the functions with the same name to be used on `drive` nodes
// internally the `before` event is used
"start_drag" : false,
"move_node" : false,
"delete_node" : false,
"remove" : false
}
}
},
but I am still able to post files into my root directory. Should I create another <li> without rel=drive above the root directory?
Thanks.
The solution for cookies in multiple trees:
.
.
"cookies": {
"save_selected": "node_selected_" + tree_id
"save_opened": "node_opened_" + tree_id
},
.
.
There is no such option as "prefix". "save_selected" and "save_opened" take either a string or false. By providing different tree_id you effectively use different cookies for each tree.

Categories