using a variable in mongodb update - javascript

Using Meteor, I'm trying to perform an update like the following:
Items.update(Session.get('selectedItem'), {'$set': {'directions.0.name': area.value}})
But I'm struggling with how to set the array index of directions dynamically, with something like this:
var index = //a value determined dynamically
Items.update(Session.get('selectedItem'), {'$set': {'directions[index]name': area.value}})
This doesn't work because [index] is wrapped in a string. I also tried to form a custom string, like this:
var string = 'directions.'+itemIndex+'.name'
Items.update(Session.get('selectedItem'), {'$set': {string: area.value}})
But that doesn't work. Any idea on how to do this?

You need to build up your $set object programmatically:
var setModifier = { $set: {} };
setModifier.$set['directions.' + index + '.name'] = area.value;
Items.update(Session.get('selectedItem'), setModifier);
Update
If your JavaScript environment supports computed property names (e.g. node.js 4+), you can do this in one step:
Items.update(Session.get('selectedItem'), { $set: {
['directions.' + index + '.name']: area.value
}});

Related

How to store value in localStorage with certain format

how can I have a localStorage value stored as
I have the value as:
ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew
but its like it has an arrow to expand and shows the same value only without the {}, an also how do I insert those keys with the slash and 2dots, have the value inside "", I thought it was an object but after trying to insert the value in a variable
var lsvalue = {
/: "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew",
}
localStorage.setItem('rmStore', JSON.stringify(lsvalue))
but it did not work, any thoughts?
tried to code mentioned
Store it as a string, the debug tool is automatically interpreting this as an object.
var lsvalue = '{"/":"ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew"}';
localStorage.setItem( 'rmStore', lsvalue )
If I'm understanding this correctly, you want your value to be just this string: "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew".
So, you can just assign that string alone to lsvalue, and set it to localStorage:
var lsvalue = "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew";
localStorage.setItem('rmStore', lsvalue);
Or just set that string as the value:
localStorage.setItem('rmStore', 'ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew');
Both of the above solutions result in the below:
But, if you're looking to set an object to localStorage:
var lsvalue =
{
'storedObject' : "ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew"
}
localStorage.setItem('rmStore', JSON.stringify(lsvalue));
This setup results in the below:

Push data into existing array using javascript

I am trying to find a way to build my custom array, but I am not able to do so.
What I have done so far:
I have my array constructed like so:
const super_array = [];
super_array.push({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
});
Further down into the code, I want to assign new data to the array, like so :
for(let j=0; j<results.length; j++) {
priceNumber = parseFloat(results[j].replace('<span>Lei</span>', '')) ;
super_array.push({price: priceNumber})
}
Result:
Right now, I get the following structure:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
}, {pret: priceNumber});
What I would like to get is:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit,
pret: priceNumber
});
I am not sure if I have explained it correctly. Basically I want to have the priceNumber uniquely match with the other data in the existing array, and not to be added as a separate index.
super_array[0].pret = priceNumber
super_array.push adds a new object to the array. What you are trying to do in the last code is adding a property to an object of the array.
For example: super_array[0].pret = priceNumber will add the property pret with the value of priceNumber. Here I'm not adding new objects to the array.

How do I set multiple values of a JSON object?

So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply

JavaScript selecting Object Arraylike?

The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name

Delete a field from Firestore, with a dynamic key

I am trying to delete a single field from a Document in Firestore
The Key of the field is held in a variable e.g.
var userId = "random-id-1"
In the document I have a field of members structured like this:
{
members:{
random-id-1:true,
random-id-2:true
}
}
I would like to delete random-id-1:true, but keep random-id-2:true
How is this possible without getting the entire members object and writing an updated object?
I have tried this, however I get the error: Document references must have an even number of segments
and I also tried this:
db.collection('groups').doc(this.props.groupId).set({
members: {
[userId]: firebase.firestore.FieldValue.delete()
}
},{merge: true})
However I get the error: Function DocumentReference.update() called with invalid data. FieldValue.delete() can only appear at the top level of your update data
Thanks for any help
I have managed to delete a field like this:
let userId = "this-is-my-user-id"
let groupId = "this-is-my-group-id"
db.collection('groups').doc(groupId).update({
['members.' + userId]: firebase.firestore.FieldValue.delete()
})
This is using the dot operator method described here
Please let me know if there are any alternative methods to this
Thanks
I had to import FieldValue
https://firebase.google.com/docs/firestore/manage-data/delete-data#fields
// Get the `FieldValue` object
var FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
var cityRef = db.collection('cities').doc('BJ');
// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
capital: FieldValue.delete()
});

Categories