How to get only data without any metadata from cloud firestore? - javascript

Is it possible to fetch only data from Cloud Firestore?
Right now I am fetching all documents from a collection, then I use loop to get the only data I saved already to Firestore as below:
const data = {};
const snap = await db.collection("rooms").where("ppl","array-contains", myUsername).get({source:"cache"});
for (let i = snap.size -1; i >= 0; i--){
const {room} = snap.docs[i].data();
const snapshot = await db.collection(`rooms/${room}/msgs`).orderBy("dt","desc").limit(50).get({source:"cache"});
const tempMessages = [];
if (len2 > 0) {
for (let k = 0; k < len; k++) {
tempMessages = [...tempMessages, snapshot.docs[k].data()];
}
}
data = { ...data, [room]: tempMessages};
}
setRoomsMessages(data);
Now what I want ???
I want to fetch only and only array of snapshot.docs[k].data() (needed data).
Why ? because I want to fetch needed data and then pass it to state directly. There is, I dont need for two nested loop I only loop the rooms and not for every room messages.

Related

Merging 2 arrays, with specified items

I stuck with joining 2 arrays.
I fetch data from 2 API, in response I got 2 different arrays, what I want to achive is one array with joined and selected arguments.
const skills = ref([]);
const entries = axios.get(`https://cdn.contentful.com/spaces/${space_id}/environments/${environment_id}/entries?access_token=${access_token}`);
const assets = axios.get(`https://cdn.contentful.com/spaces/${space_id}/environments/${environment_id}/assets?access_token=${access_token}`);
axios
.all([entries, assets])
.then(
axios.spread((...responses) => {
const responseEntries = responses[0].data.items.map(
(item) => item.fields
);
const responseAssets = responses[1].data.items.map(
(item) => "https:" + item.fields.file.url
);
const checkEntries = Array.isArray(responseEntries);
const checkAssets = Array.isArray(responseAssets);
console.log(checkEntries);
console.log(checkAssets);
console.log(responseEntries);
console.log(responseAssets);
for (let i = 0; i < responseEntries.length; i++) {
skills[i].value = [
responseAssets[i],
responseEntries[i].title,
responseEntries[i].list,
responseEntries[i].description,
];
}
})
)
.catch((error) => console.log(error));
I'm getting error:
TypeError: Cannot set properties of undefined (setting 'value')
Here is what I got in console, and the how arrays looks
Thank you! Your answer help me to rethink that problem and finally I solved it in different way I added a value to first array.
for (let i = 0; i < responseEntries.length; i++) {
responseEntries[i].url = responseAssets[i];
}
skills.value = responseEntries;
Your problem is certainly inside the for loop, where you try:
skills[i].value = [...]
at that point, skills[i] doesn't exist so you have to initialize it before into an object, so:
for (let i = 0; i < responseEntries.length; i++) {
skills.value[i] = {}
skills.value[i] = [
responseAssets[i],
responseEntries[i].title,
responseEntries[i].list,
responseEntries[i].description,
];
}
I still don't understand the first line, though, const skills = ref([]); where, imho, should just be const skills = []

Alter a object variable inside cloud functions

I am trying to alter a object variable after query in cloud functions, but before sending it to my app, but not sure how to do so! Here is what I am trying to do:
Parse.Cloud.define("getUserData", async(request) => {
// Getting the users data
const userQuery = new Parse.Query("UserData");
userQuery.equalTo("userId", request.params.userId);
const userData = await userQuery.first();
// Getting the groups
const groupQuery = new Parse.Query("GroupMembers");
groupQuery.equalTo("userId", request.params.userId);
groupQuery.include('pointerObject'); // including the pointer object
const groups = await groupQuery.find();
const allGroups = [];
for (let i = 0; i < groups.length; ++i) {
var thisGroup = groups[i].get("pointerObject");
thisGroup.isFavorite = true;
allGroups.push(thisGroup);
}
var returnObject = {
"playerData": userData,
"playerGroups": allGroups
}
const jsonString = JSON.stringify(returnObject);
return jsonString;
});
It is "thisGroup.isFavorite" i am trying to set to true, but when receiving the jsonString, it is still set to false? How do I alter a variable in cloud functions?
Any help is appreciated and thanks in advance :-)
Try with:
thisGroup.set('isFavorite', true);
await thisGroup.save();

Attach CSV data to my API JSON data in Angular application, on subscribe

I need to take data from a CSV file and attach it to the main JSON I use for my Angular app.
More specifically, I need to take the life expectancies from the CSV file and attach them to the matching country of the JSON (the JSON data is an array of objects, of length 212 and the CSV data is of length 200).
I use d3.js to parse the CSV file. I tried this but it doesn't seem to work. The getData method that I subscribe, is the main source of data, in which I want to attach life expectancy.
this.store.getData().subscribe((data: Data[]) => {
d3.csv('../assets/datasets/life_expectancy.csv').then((csvData: any) => {
for (let i = 0; i < csvData.length; i++) {
if (csvData[i].country_name === data[i].country) {
data[i].lifeExpectancy = csvData[i].country_life_expectancy;
}
}
});
The life expectancy CSV is like this ([{country_name: 'United States', {country_life_expextancy: 79.11}}...])
Finally, I came up with a solution:
data: Data[];
ngOnInit() {
this.store.getData().subscribe((data: Data[]) => {
this.data = data;
d3.csv('../assets/datasets/life_expectancy.csv').then((csvData: any) => {
for (let i = 0; i < csvData.length; i++) {
for (let j = 0; j < this.data.length; j++) {
if (csvData[i].country_name === this.data[j].country) {
this.data[j].lifeExpectancy = csvData[i].country_life_expectancy;
}
}
}
});
}

Enmap (better-sqlite map) doesnt update until application is restarted

This is a code Snippet from a discord bot im working on
It needs to load up data from an Enmap, adds information to that Array and then pushes it back in.
It successfully pulls that data, does all the transformations and additions, etc
and successfully pushes that data
however, it cant pull the new data until the program is re-started. It gets saved but
let locationDataArray = await data.get(locationDataKey);
doesnt seem to do pull this new version of the map unless the program is restarted
I am fairly stumped
const Commando = require('discord.js-commando');
const levenshtein = require('fast-levenshtein');
const Enmap = require("enmap");
const data = new Enmap({
name:"locationdata"
});
const settingsMap = new Enmap({
name:"locationSettings"
})
module.exports = class addConnection extends Commando.Command{
constructor(client){
super(client, {
name:"addconnection",
group:"management",
aliases:["connect"],
memberName:"addconnection",
userPermissions:['ADMINISTRATOR'],
description:"adds a connection between two zones",
examples: ['$addconnection <zone1>,<zone2>'],
throttling: {
usages: 1,
duration: 5
},
args:[{
key:'destinations',
prompt:'what are the two areas you want to connect (seperate them with a comma , )',
type:'string'
}]
});
}
async run(msg,args){
//get our guilds Information
let guildID = msg.guild.id;
let locationDataKey = guildID+"_mapData";
let locationDataArray = await data.get(locationDataKey);
//Our Guild Settings
let settingMapKey = guildID+"_setting";
let settings = await settingsMap.get(settingMapKey);
//chiefly out npcRoleID
let npcRole = await msg.guild.roles.get(settings.npcRoleID);
let connectionArray = await args.destinations.toLowerCase().split(",");
for(var i = 0; i < connectionArray.length; i++){
//make sure the item is valid
var distance = levenshtein.get(connectionArray[i], locationDataArray[0].name);
var closestDistance = distance;
var closestWord = locationDataArray[0].name;
for(var j = 0; j < locationDataArray.length; j++){
distance = levenshtein.get(connectionArray[i], locationDataArray[j].name);
if (distance < closestDistance){
closestDistance = distance;
closestWord = locationDataArray[j].name;
}
}
//make sure all the areas are valid and good
if(closestDistance < (closestWord.length/2)){
connectionArray[i] = closestWord;
}
else{
msg.channel.send("those channels don't seem to exist").then( msg => {
msg.delete(10000);
});
return;
}
}
//our array of connections now only contains valid options
//loop over our location data array
for(var i = 0; i< connectionArray.length; i++){
for(var j = 0; j < locationDataArray.length; j++){
//when we hit one of out LDA that has the same name as something in the connectionArray
//stop add the rest of the connection array to its connections
if(locationDataArray[j].name === connectionArray[i]){
for(var k = 0; k < connectionArray.length; k++){
if(locationDataArray[j].name == connectionArray[k]){
}
else{
if(!locationDataArray[j].connections.includes(connectionArray[k])){
await locationDataArray[j].connections.push(connectionArray[k]);
}
//get the role for the connection and the current channel
let role = await msg.guild.roles.find(role => role.name === connectionArray[k]);
let currentChannel = await msg.guild.channels.find(channel => channel.name === locationDataArray[j].channelName);
//the connection can read but not type in its connection
currentChannel.overwritePermissions(
role,
{
'SEND_MESSAGES':false,
'VIEW_CHANNEL':true,
'READ_MESSAGE_HISTORY':true
}
)
data.set(locationDataKey, locationDataArray);
msg.channel.send("Connected "+locationDataArray[j].name+" and "+connectionArray[k]);
}
}
}
}
}
}
}
I know this question is old and I'm hoping you've resolved this issue a long time ago, but for posterity's sake, and because people might find this question later, I'm going to answer it anyways.
The reason this happens is that you're creating a new instance of Enmap in this file, and presumably you have it declared in other files too. This causes a new "client" for Enmap to be created, with its own individual cache, and it's not possible for Enmap to update those instances.
The solution is to either attach your Enmap to a variable you carry around (such as, for example, the Client), or to create a separate node module that you import wherever you need it. Both of those options are described in more details in the Enmap documentation: https://enmap.evie.dev/usage/using-from-multiple-files
Disclaimer: I am the author of Enmap

Need Help to adding new array into JSON object

I'm making an file managing web page with nodejs and need some help.
I'm adding some informations into JSON object which recieved from DB.
the DB constains stage informations and I should link informations about stage files.
this is code for the function. Added comments into codes.
DBmodel.findOne({'key': 'server'}).exec(function (err, data) {
for (var i = 0; i < data.stage.length; i++) {
// this was successful. I added an array to check each files.
data.stage[i].packFileNameArray = data.stage[i].packFileName.split("/");
data.stage[i].packVersionArray = data.stage[i].packVersion.split("/");
// this is a problem. I will add file information for each file.
// I
for (var j = 0; j < data.stage[i].packFileNameArray.length; j++) {
fs.stat(dirPath + data.stage[i].packFileNameArray[j], function (err, fileStat) {
if (err) {
// this was first try. I thought the array will be automaticallt created.
data.stage[i].isExist[j] = 'NO';
data.stage[i].mTime[j] = '0';
data.stage[i].size[j] = '0';
} else {
// this was second try. I tried push into each time.
data.stage[i].isExist.push('YES');
data.stage[i].mTime.push(fileStat.mTime);
data.stage[i].size.push(fileStat.size);
}
console.log(data.stage[i].isExist[j]);
console.log(data.stage[i].mTime[j]);
console.log(data.stage[i].size[j]);
});
}
}
});
I want to know how I can add additional informations as an array into the JSON object.
Thank you.
data.stage[i].push({ isExist: 'Yes'});
etc
You have to create the arrays (as the do not seem to exist) before you can push data into them:
DBmodel.findOne({'key': 'server'}).exec(function (err, data) {
for (var i = 0; i < data.stage.length; i++) {
// this was successful. I added an array to check each files.
data.stage[i].packFileNameArray = data.stage[i].packFileName.split("/");
data.stage[i].packVersionArray = data.stage[i].packVersion.split("/");
data.stage[i].isExist = [];
data.stage[i].mTime = [];
data.stage[i].size = [];
//...

Categories

Resources