Dynamic key name for mongodb Realm - javascript

I'm making a digital Christmas Kalendar for a friend. Every day he can claim a Steam game.
So in mongodb in the user account that I made for him there is a key called codes (object). The structure is as follows:
_id: blbalbalba
codes: {
1 : {
title: GTA V,
code: AISHD-SDAH-HAUd,
claimed_at: ,
},
2 : {
title: Fortnite,
code: HHF7-d88a-88fa,
claimed_at: ,
}
}
Just example data. Now in the client app, when button (door) 7 is pressed/opened I want to insert the current date to the key "claimed_at" in the object with key name "7".
I tried some variations of:
const result = await PrivateUserData.updateOne(
{ id: myID },
{ $set: { "codes.`${door_number}`.date_claimed" : date,
}
}
);
But this doesn't work. What did work was: "codes.5.date_claimed". So a static path. In that case the object with name 5 got it's date_claimed key updated.
But how do I use a dynamic path with a variable instead of a number?
Thanks in advance!

If you know the variable value before calling the query i think both of the bellow can work.
var door_number=5;
var date= new Date("...");
const result = await PrivateUserData.updateOne(
{ id: myID },
{ $set : { ["codes."+door_number+".date_claimed"] : date}}
);
var door_number=5;
var date= new Date("...");
const result = await PrivateUserData.updateOne(
{ id: myID },
{ $set : { [`codes.${door_number}.date_claimed`] : date}}
);
If the dynamic behaviour is based on information on the database, send if you can sample data and expected output, so we know what you need.

Related

make the query dynamically to change using sanity.io groq

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.
Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

Best way to update value of an object inside mongodb object

This is how I store each element in my mongodb collection.
{
_id: 'iTIBHxAb8',
title: 'happy birthday',
votesObject: { happy: 0, birthday: 0 }
}
I made a very dirty work around which I am not at all proud of which is this...
//queryObject= {id,chosenvalue};
let queryObject = req.query;
let id = Object.keys(queryObject)[0];
let chosenValue = queryObject[id];
db.collection("voting")
.find({ _id: id })
.toArray((err, data) => {
let { votesObject } = data[0];
votesObject[chosenValue] += 1;
data[0].votesObject = votesObject;
db.collection("voting").replaceOne({ _id: id }, data[0]);
res.redirect("/polls?id=" + id);
});
So basically what this does is It gets the chosen value which may be "happy" or the "birthday" from the above example.
Finding the complete object from the collection which matches the id.
Incrementing the chosen value from the found object.
Using replaceOne() to replace the previous object with the newly changed object.
I am incrementing the value inside chosen value by one everytime this piece of code executes.
This works perfectly fine but I want to know if there is any way to directly update the chosen value without all this mess. I could not find a way to do it else where.
you can use mongoose findOneAndUpdate
It will be something like
const updateKey = "votesObject.$."+ chosenValue
let incQuery = {}
incQuery[updateKey] = 1
Model.findOneAndUpdate(
{ _id: id },
{ $inc: incQuery },
{ new : false },
callback
)
You can use $inc operator.
Try something like this:
db.collection.update({
"_id": id
},
{
"$inc": {
"votesObject.birthday": 1
}
})
This query will increment your field birthday in one.
Check mongo playground exaxmple here

how can i replace one value from list object and same new value assign to same object list using angularjs?

var test = list contains 10 rows with 4 columns;
test.then(function(d)){
$scope.mylist = d.data;
}
example:my list contains one row like
name:"rajesh";
id:10009;
branch:"dotnet";etc...
here i want to replace branch dotnet to angular for all rows and again that value assign same to same object.
means i need output like this?
name:"rajesh";//1st row
id:100009;
branch:"angular";
name:"sai";//2nd row
id:1004;
branch:"angular"; like this
please suggest i am new to angularjs
FYI, You are using very old JavaScript syntax. (Recommended to upgrade)
Anyways, extending the code snippet in your question.
Update
question is different from what you are asking in comments. if you are looking for code to get it done. Here it is...
const results = [
{ Name: 'raju', Id: 1009, Branch: 'cse' },
{ Name: 'sai', Id: 1019, Branch: 'ece' },
{ Name: 'nandu', Id: 1089, Branch: 'civil' }
];
const output = results.map(user => {
user.Name = '****';
return user;
});
Just use map to transform your data.
var test = list contains 10 rows with 4 columns;
test.then(function(d)){
$scope.mylist = d.data.map(function(user) {
if (user.branch === 'dotnet') {
user.branch = 'angular';
}
return user;
});
}

Get unique id of specific element in Firebase

I have my Firebase database structured like this:
{
"userProfile" : {
"X0u2SEFfYEeVmdw4TXl58ou2eYy1" : {
"email" : "jane#yahoo.com",
"name" : "Jane"
},
"cliv7hQ4FsWKTtYksPDXcdDafdi2" : {
"email" : "doe#gmail.com",
"name" : "John Doe",
}
}
}
I'm trying to get the unique id of the element that matches query criteria, for example the key of the element with email equal to doe#gmail.com.
I'm doing this by using:
firebase.database().ref('/userProfile').orderByChild('email').equalTo(email).once( 'value', data => {
let user = data.val();
});
This returns me the entire object with that email, but I only want its unique id ("cliv7hQ4FsWKTtYksPDXcdDafdi2" in this case). What's the best way to achieve this?
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
So:
var query = firebase.database().ref('/userProfile').orderByChild('email').equalTo(email);
query.once( 'value', data => {
data.forEach(userSnapshot => {
let user = userSnapshot.val();
let key = userSnapshot.key;
});
});

Firebase push - deletes unique object and inserts new one (Overwrites content basically)

I have an application that is running with firebase. When I try to use the push() method, it basically overwrites the existing JSON. Here's an example:
First time around, the following JSON is generated:
JSON
"deviceIDs" : {
"-JzCx5C_13eoXPEgklMW" : {
"author" : "gracehop22",
"deviceID" : "99alpha",
"title" : "Announcing COBOL, a New Programming Language"
}
}
Next time around, if I call the same function, the above JSON is deleted and a new JSON is inserted such as this one:
JSON
"deviceIDs" : {
"-JzCxbuEj2V1kmvvgqnc" : {
"author" : "gracehop22",
"deviceID" : "99alpha",
"title" : "Announcing COBOL, a New Programming Language"
}
}
Here's my code snippet:
function CreateUserProfile(UID, name, email, deviceID) {
var ref = new Firebase($scope.firebaseurl + '/' + UID);
var profileArray = {UserProfile:{}};
profileArray.UserProfile.UID = UID;
profileArray.UserProfile.name = name;
profileArray.UserProfile.email = email;
profileArray.UserProfile.deviceID = deviceID;
var onComplete = function (error) {
if (error) {
console.log('Synchronization failed');
} else {
//1. On Success, Store Key User Profile Elements
localStorage.setItem("kasimaProfileInfo",JSON.stringify(profileArray));
$rootScope.username = name;
//2. Hide the feedback and change screens
$timeout(function () {
$scope.HideFeedback();
$scope.ChangeLoc('/featured');
}, 1500);
}
};
ref.set(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
var newPostRef = postsRef.push();
newPostRef.set({
deviceID: deviceID,
author: "gracehop22",
title: "Announcing COBOL, a New Programming Language"
});
}
You're overwriting the entire ref when you're setting profileArray:
...
ref.set(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
...
You'll probably want to use update() there:
...
ref.update(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
...
Update
The Firebase update() functions set the value of the properties in the JSON object you pass it. So your new profileArray.UserProfile will replace the existing data.
The solution is to not build a nested JSON structure locally, but instead update the data at the lower location where it needs updating:
ref.child('UserProfile').update(profileArray.UserProfile, onComplete);
This removes the entire need for the profileArray:
var userProfile = {
UID: UID,
name: name,
email: email,
decideID: deviceID
};
ref.child('UserProfile').update(userProfile, onComplete);
For a working example, see: http://jsbin.com/ciqoge/edit?js,console
For a next time: if you provide such a jsbin/jsfiddle straight away, it will be much easier to quickly help you.

Categories

Resources