I have a query function like:
const DATABASE_COLLECTION_NAME = "users";
let mongoConnection = null;
let db = null;
const findDocuments = async(value) => {
console.log("this is value: ", value)
// response is: "clientId": "e0bb610d-05d4-4df1-8ab8-5a009ec953ef"
// but after I put it in below query
const query = { value };
console.log("this is query: ", query)
// response is: { value: '"clientId": "e0bb610d-05d4-4df1-8ab8-5a009ec953ef"' }
if (!db)
throw Error('findDocuments::missing required params');
const collection = await db.collection(DATABASE_COLLECTION_NAME );
return await collection.find(query).toArray();
};
As comment above I don't know why it's convert to like this When I put it in query variable, so that is the reason I can not query data from Mongo cosmosDb
{ value: '"clientId": "e0bb610d-05d4-4df1-8ab8-5a009ec953ef"' }
I just wanna be like this
{ "clientId": "e0bb610d-05d4-4df1-8ab8-5a009ec953ef" }
I have try this function to get that json object correctly:
const valueJSON = JSON.parse("{" + query.value + "}")
but the result is: { clientId: 'e0bb610d-05d4-4df1-8ab8-5a009ec953ef' }
not like this: { "clientId": "e0bb610d-05d4-4df1-8ab8-5a009ec953ef" }
Good day, I'm trying to get certain values with api the maximum that I can do is output all the json
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { data } = json;
console.log(data)
}
getData();
please could tell me how to get the element, I tried like this:
const api_url = 'https://api.battlemetrics.com/servers/3753675'
async function getData() {
const response = await fetch(api_url);
const json = await response.json();
const { name, id, status } = json;
console.log(name, id, status)
}
getData();
but i get "undefined undefined undefined"
The object I asked for:
{"data":{"type":"server","id":"3753675","attributes":{"id":"3753675","name":"Rusticated.com Sandbox - Creative | Minigames | Bedwars\r","address":null,"ip":"199.231.233.240","port":28015,"players":201,"maxPlayers":1000,"rank":1,"location":[-87.618889,41.875744],"status":"online","details":{"official":false,"rust_type":"modded","map":"BuildBattleArenaScrimGames","environment":"w","rust_ent_cnt_i":0,"rust_fps":43680,"rust_fps_avg":43680,"rust_gc_cl":null,"rust_gc_mb":null,"rust_hash":"","rust_headerimage":"https://cdn.discordapp.com/attachments/811789078105554984/832668733184671754/Rusticated_Mini_Games_Banner_512x256.png","rust_mem_pv":null,"rust_mem_ws":null,"pve":false,"rust_uptime":null,"rust_url":"https://rustminigames.com","rust_world_seed":1337,"rust_world_size":null,"rust_description":"Rusticated Minigames Beta \n Bedwars \n Creative \n GunGame \n Targets \n More Coming Soon...","rust_modded":true,"rust_queued_players":0,"rust_born":"2022-06-05T00:00:00.000Z","rust_last_ent_drop":"2021-08-06T00:10:18.261Z","rust_last_seed_change":"2020-09-03T18:33:52.047Z","rust_last_wipe":"2021-08-06T00:10:18.261Z","rust_last_wipe_ent":29035,"serverSteamId":"90159726978107400"},"private":false,"createdAt":"2019-06-18T18:35:26.890Z","updatedAt":"2022-06-06T10:05:57.516Z","portQuery":28038,"country":"US","queryStatus":"valid"},"relationships":{"game":{"data":{"type":"game","id":"rust"}}}},"included":[]}
If you want to get object you said, try this.
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
console.log(json); // you need to check json first. (*)
}
getData();
Then you can use destructuring.
const API_URL = 'https://api.battlemetrics.com/servers/3753675';
async function getData() {
const response = await fetch(API_URL);
const json = await response.json();
const { name, id, status } = json.data.attributes; // (*)
console.log(name, id, status);
}
getData();
You just need to replace:
const { name, id, status } = json;
with:
const {
data: {
id,
attributes: { name, status }
}
} = json;
because your keys are not directly into the response, but nested.
I have problem with my code, problem is i get array from server with async function (getData()) and then i want push one object into it but it doesn't work and have error like this :
sandbox.js:61 Uncaught TypeError: Cannot read properties of undefined (reading 'push')
at submitData (sandbox.js:61)
at handleInputs (sandbox.js:44)
at HTMLButtonElement.<anonymous> (sandbox.js:35)
and the code is here :
var dataBase;
const getData = async() => {
const url = 'http://localhost:8080/readData';
const res = await fetch(url);
const data = awair res.json();
dataBase = data;
}
const handleInputs = () => {
if (userName.value === "" && password.value === "" && repeatPassword.value === "" && checkTerms.checked) {
alert('Please fill the input');
} else {
if (password.value === repeatPassword.value) {
getData();
submitData();
renderUser();
form.reset();
} else {
alert('Password does not match with repeat password input')
}
}
}
const submitData = () => {
let userObj = {
userName: userName.value,
password: password.value,
id: countId++
}
dataBase.push(userObj); // problem here
sendData();
}
and how can i fix it ?
Here, I have removed the functions not declared here for now. You can add it later.
You are getting this error because you have not initialized database with any value, here an array
I am returning Promise to wait till the user is fetched.
Note: You were having the same variable dataBase for saving newly fetched data. I have created a new data variable for saving newly fetched data and database variable for saving it for further use.
let newData;
let dataBase =[];
const getData = () => {
return new Promise(async(resolve, reject) => {
const url = 'https://jsonplaceholder.typicode.com/users/1';
const res = await fetch(url);
const data = await res.json();
console.log(data);
newData = data;
resolve();
})
}
const handleInputs = async () => {
await getData();
submitData();
console.log("database", dataBase);
}
const submitData = () => {
let userObj = {
userName: newData.username,
password: newData.email,
id: newData.id
}
//it is showing undefined as you have not initialized database with any value, here an array
dataBase.push(userObj);
}
handleInputs();
I try to get specific documents from MongoDB with Node.js and insert them into array.
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
comments.forEach(async (commentId) => {
const comm = await commentModel.findOne({ _id: commentId });
data.push(comm);
console.log(data); // This returns the data in loops, because its inside a loop.
});
console.log(data); // This not returns the data and i don't know why.
return data;
};
The first console.log(data) returns the same data a lot of times because its inside a loop.
But the second console.log(data) dosen't returns the data at all.
What I'm doing wrong?
Instead of using loop , you can use $in operator to simplify things .
const getStockComments = async (req) => {
const stockname = req.params.stockName;
var comments = [];
var data = [];
const stock = await stockModel.findOne({ name: stockname });
comments = stock.comments;
commentModel.find({ _id: { $in: comments } }, (err, comments) => {
data = comments;
});
console.log(data);
return data;
};
I'm trying to create a function with firebase, where upon request the function carries out some scraping activites and then logs the result to a collection each time. My function works and returns the Array of items that I need, but I am having trouble then adding this array to the firestore database.
I am not sure if I need to subscribe to the response or if it is returning something else.
Cloud Function:
exports.scraper = functions.https.onRequest( async (request, response) => {
cors(request, response, async () => {
const body = (request.body);
const data = await scrapeteamtags(body.text);
response.send(data)
});
return admin.firestore().collection('games').add({
teams: data
})
});
Added the function used in the await for context:
const scrapeteamtags = (text) => {
const urls = Array.from( getUrls(text) );
const requests = urls.map(async url => {
const res = await fetch(url);
const html = await res.text();
const $ = cheerio.load(html);
const getTeamlist = JSON.parse($('body').text())
var gamelist = {
games: []
}
getTeamlist.SSResponse.children.map(function(item) {
// go into the returned json
var event = new Object;
var leagues = ["Premier League", "Spanish La Liga", "Italian Serie A", 'French Ligue 1', 'German Bundesliga']
// finds all child items that contain the event tag
if(Object.keys(item).includes('event')) {
// check that the league is on the list which are of interest
if(leagues.includes(item.event.typeName)) {
event.id = item.event.id;
event.name = item.event.name;
// add the event name and id to the object then go into next level to get market data
item.event.children.map(function(item1) {
if(Object.keys(item1).includes('market')) {
event.marketid = item1.market.id
// add the market data id to the object
var eventoutcome = []
item1.market.children.map(function(item2) {
if(Object.keys(item2).includes('outcome')) {
eventoutcome.push({"id" : item2.outcome.id,
"id": item2.outcome.id,
"name": item2.outcome.name,
"price": item2.outcome.children[0].price.priceDec})
//adds the id, name and price to an array, then add it to the object
event.outcome = eventoutcome
}
})
}
})
gamelist.games.push(event)
}
// push each event as a new object to the array of games
}
})
//console.log(gamelist.games)
return {
gamelist
}
});
return Promise.all(requests);
}
HTTP functions don't let you return a promise with the data to send. (That's how callable functions work, but that doesn't apply here.) You will have to wait for the database write to finish, then send the response to terminate the function.
The function should be structured more like this:
exports.scraper = functions.https.onRequest( async (request, response) => {
cors(request, response, async () => {
const body = (request.body);
const data = await scrapeteamtags(body.text);
await admin.firestore().collection('games').add({
teams: data
})
response.send(data)
});
});