Javascript - delete object from reference - javascript

I have one tree-like structure containing block with certain id. Then I have another object, that contains 'id' : objectPart pairs.
Tree:
var tree = [
{
'property' : 'value',
'id' : 'someID',
//more properties...,
'content' : [
{
'prop' : 'something',
...
}
]
},
{
'prop' : 'val',
...
'content' : []
}
]
ID index:
{
'someID' : tree[0]
}
I need some way how when I do delete ID_index.someID, that object gets also deleted from main structure.
Structure after this code should look like this:
[
{
'prop' : 'val',
...
'content' : []
}
]

Instead of using delete you can write your own remove function. It should look like this:
function myRemove(stringId) {
delete ID_index[stringId]; //remove property from ID_index
objIndex = ... //find object index in tree array
tree.splice(objIndex, 1); //remove object from tree array
}

Related

Mongoose update specific fields in entire array of objects

In a mongoose document I have a array of objects, something like this :
{
name : 'helloWorld',
arr : [
{ a : 'id1', b : 'sampleValue1', c: 'sampleValue2'},
{ a : 'id2', b: 'tempValue1', c:'tempValue2'}
]
}
In the array of objects 'arr' I want to update all the values of field 'b' and 'c' with specific values, how can I do that elegantly?
I know for a single element of the array I can do (it works) :
Model.updateOne(
{
name : 'helloWorld;,
'arr.a' : 'id1',
},
{
'arr.$.b' : 'newB',
'arr.$.c' : 'newC',
}
);
But how to do it elegantly for the entire array ?
I know I can do it using multiple queries via forEach looping for each of the 'arr.a' field, but I want an elegant preferable single query method for this.

How to rename my property value but keep the other infos?

I have an object like this:
The thing I want to do is to rename the services.XXX value but keep his child properties.
For example I want to rename object.services.cadvisor with object.services.new-name
How can I do that ?
You can do the following
object.services.newName = object.services.cadvisor;
delete object.services.cadvisor
Copy the object to the new property and delete the old one
let myObj = {
services: {
cadvisor : {
name: 'Cadivsor',
length: 50,
nestedObject : {
name: 'Nested'
}
},
other : {}
}
};
myObj.services['newName'] = myObj.services.cadvisor;
delete myObj.services.cadvisor;
console.log(myObj);

mongoDB: Find missing documents in model tree structure with parent reference

I have some documents which are organized in a model tree structure (depth is variable!). Unfortunately some documents are missing and I need to find those broken chains. As you can see the last document in that chain has always the target field. This is the starting point and I have to look upwards using parent. The last element in that chain has always the field type.
{
"_id" : "K7NSxNEnNSr9nCszR",
"title" : "title",
"type" : "book",
"ancestors" : [ ]
}
{
"_id" : "diyvwYz66yoTCTt9L",
"field" : "something",
"parent" : "K7NSxNEnNSr9nCszR",
"ancestors" : [
"K7NSxNEnNSr9nCszR"
]
}
{
"_id" : "diyvwYz66yoTCTt9L",
"field" : "anything",
"target" : "D2YuXtM6Gzt4eWaW2",
"parent" : "QWvdAyftSGANM3zy8",
"ancestors" : [
"K7NSxNEnNSr9nCszR",
"QWvdAyftSGANM3zy8"
]
}
What I need to know is if any parent is missing or if the last element (=type existing) is missing.
var broken = [];
Collection.find({ target: { $exists: true }}).forEach(function(element) {
var startDocID = element._id;
if (Collection.find({ _id: element.parent }).count() === 0)
broken.push(startDocID);
});
console.log(broken);
But this isn't working well as I need to use a loop to get upwards until the top document (= type existing).
You're talking about recursion here if you need to go down the tree, so you probably need to write a recursive search function
var broken = [];
Collection.find({ target: { $exists: true }}).forEach(function(element) {
function recurse(e) {
var startDocID = e._id;
var nodes = Collection.find({ _id: e.parent });
if (node.count() === 0)
{broken.push(startDocID);}
else {
nodes.fetch().forEach(node) {
recurse(node)
}
}
recurse(element);
}
});
or something of that sort... (hard to debug without the data)

Create a JSON object with variables as fields

I want to create a JSON object with variables as associative variable names similar to the following:
var field = 'first';
var query = { details.field, details.field };
I would prefer if the details were a fixed value.
This is my dataset currently
{
field1: ,
group: {
first:
}
}
My question is, how would I go about creating JSON objects with variables as fields?
You can add a property to an object like so:
var query = { details: {} };
var field = 'first';
query.details[field] = "TEST";
Which will give you the object:
{ details: { first: "TEST" }}
which you can then access with query.details.first or query.details[field];
Is that what you're looking for?
A simple way to accomplish this in Javascript is using the . operator.
query.details.field = "first";
This will product an object as follows:
"query" { "details" { "field": "first"} }
Is this what your looking for?
If you want multiple details you will want to use an array.
var query = [];
query.push({"details" { "field" : "first"} });
query.push({"details" { "field" : "second"} });
This will product an object like this
"query" [
"details" { "field" : "first"},
"details" { "field" : "second"}
]

Backbone collection tree creation

I'm using backbone 1.1 and trying to create a collection from a 3-5 level deep tree-navigation.
A simplified version of my code looks like this.
var treeItem = Backbone.Model.extend({
defaults : {
'label' : '',
'children' : null
},
initialize : function() {
console.log('model init');
if (_.isArray(this.get('children'))) {
this.set({children : new treeItemCollection(this.get('children'))});
}
},
});
var treeItemCollection = Backbone.Collection.extend({
model: treeItem
});
var myTree = new treeItemCollection([
{ "label" : "first", "id": 1 },
{ "label" : "second", "id": 1, "children":
[
{ "label" : "second.first", "id" : 21 },
{ "label" : "second.second", "id" : 22 },
{ "label" : "second.third", "id" : 22, "children" : [
{ "label" : "third.first", "id" : 31 },
{ "label" : "third.second", "id" : 32 }
] }
]
}
]);
In my understanding this should create the deeper level child-collections correctly (as to my understanding, initialize should be called when the object is constructed thus creating the deeper levels correctly).
For some reason this doesn't seem to be the case. The second level (eg. myTree.models[0].get('children') is correctly a collection of the treeCollection type, but the 3rd level (myTree.models[0].get('children').models[0].get('children')) is just straight up JSON from the parameter object.
To me that's the weirdest part, that the second level is ok, but the third is not. The console.log in initialize() is to check, and quite right, it gets triggered 4 times, not 6.
I'm trying to understand why the 3rd level doesn't get converted to a collection.
You can overwrite the parse function in the model to do this.
var treeItem = Backbone.Model.extend({
defaults : {
'label' : '',
'children' : null
},
initialize : function() {
console.log('model init');
},
parse: function(response) {
if (response["children"]) {
response["children"] = new treeItemCollection(response["children"]);
}
return response;
}
});
this way, each time when you do fetch() or save(), it will automatically wrap your children (and their nested children, if exists) in treeItemCollection.
But this does not work when you bootstrap your data, or you are just using reset(). so you may want to overwrite the constructor method as well:
var treeItem = Backbone.Model.extend({
//other stuff shown above
constructor: function(attributes, options){
options = options || {};
options.parse = true;
Backbone.Model.call(this, attributes, options);
}
});
and it should work for your case.
We have used this pattern in many projects and we loved it. If you wanna apply it to all models/collections, and be more flexible, you probably wanna read this:
http://www.devmynd.com/blog/2013-6-backbone-js-with-a-spine-part-2-models-and-collections

Categories

Resources