So, I have a function in my class that should return an object, but instead it returns undefined, which I dont know why it is happening, here's the code:
method.getQuests = function(){
var id = this._data[0].id;
var lvl = this._data[0].level;
var structure = [];
connection.query("SELECT * FROM quest WHERE player_id = ?", [id], function(errors, rowss, fieldss) {
for(var i = 0; i < rowss.length; i++){
var rewards = {
"coins":rowss[i].gold,
"xp":rowss[i].experience,
"honor":rowss[i].honor,
"premium":rowss[i].donut,
"statPoints":0,
"item":0
};
structure.push({
"id": rowss[i].id,
"character_id": id,
"identifier": rowss[i].name,
"type": 1,
"stage": rowss[i].stage,
"level": lvl,
"status": 1,
"duration_type": 1,
"duration_raw": (rowss[i].duration * 60) * 4,
"duration": rowss[i].duration * 60,
"ts_complete": 0,
"energy_cost": rowss[i].duration,
"fight_difficulty": 0,
"fight_npc_identifier": "",
"fight_battle_id": 0,
"used_resources": 0,
"rewards": JSON.stringify(rewards)
});
}
return structure;
});
}
What is also happening is that after I call some mysql query my user data stored in this._data doesn't exist anymore, so Im totally lost at this point.
connection.query is async, so when you return structure; it will return undefined because the async function connection.query() hasn't completed yet. Try using a callback. When you define your function, define it like this:
method.getQuests = function(callback){
And instead of return structure; try
callback(structure);
Then, when you call it and want to use it, use it like this:
method.getQuests(function(structure){
console.log(structure);
});
Related
On my current project in node.js (where I'm a beginner), there is a source of data that can be queried (WEB API) but is restricted to a certain amount of entries from a given position. It is not possible to request the full record set (eg. 1000 entries) you only can select a maximum of 50 Entries from an offset.
The function to get the data is as follow:
let myResponseData = await client.getData({userId: myId, first: 50, after: cursor});
where userId is an authentication, first is the number of records I want to request (0-50), and after is the cursor
the response looks like this:
{
"totalRecords": 1000,
"page_info": {
"has_next_page": true,
"end_cursor": "this is some random string"
},
"data": [
{
"id:" 1,
"name": "Name1"
},
{
"id:" 2,
"name": "Name2"
}
]
}
My current progress in fetching all data is, that i've already constructed a function that reads all pages from the data source like this:
let myResponseData = await client.getData({userId: myId});
let hasNextPage = myResponseData.page_info.next_page;
let cursor = myResponseData.page_info.cursor;
while(hasNextPage){
console.log('next...' + cursor);
myResponseData= await client.getData({ userId: myId, first: 50, after: cursor});
hasNextPage = myResponseData.page_info.next_page;
cursor = myResponseData.page_info.cursor;
myFunctionToJoinData(myResponseData); //Here i need help
}
This works so far since the console logs the next + random string.
My goal is to end up with a json data object like in the request, but having all the entries from all queries
How can this be achieved?
I started to work in a new project where I found lodash's flow function and I saw the uses of it here docs but in my project, in the following code, I found over there flow([...])(state) here what is (state) at the end of the function?
module.exports = (async function published(state) {
return flow([
setColumnIndex('my_pay_table', 1, 'rate_mode', getColumn('pay_structure', 'pay_per_id', state)),
setColumnIndex('my_pay_table', 1, 'rate_amount', getColumn('pay_structure', 'pay_rate', state)),
setColumnIndex('my_wo_title_table', 1, 'user_id', buildArtifact(ownerAlias, 'user', 'id', 1)),
setColumnIndex('my_wo_title_table', 1, 'date_added', Date.now() / 1000),
])(state);
});
Can anyone help me?
According to the lodash documentation, flow returns a function. In JavaScript it is possible to return functions without executing them.
We could refactor the code you provided to the following
module.exports = (async function published(state) {
// `func` here is a function
const func = flow([
setColumnIndex('my_pay_table', 1, 'rate_mode', getColumn('pay_structure', 'pay_per_id', state)),
setColumnIndex('my_pay_table', 1, 'rate_amount', getColumn('pay_structure', 'pay_rate', state)),
setColumnIndex('my_wo_title_table', 1, 'user_id', buildArtifact(ownerAlias, 'user', 'id', 1)),
setColumnIndex('my_wo_title_table', 1, 'date_added', Date.now() / 1000),
]);
// Here we execute that function with an argument `state`
return func(state);
});
So far I found the solution. It actually uses Lodash's curry function.
let state = "Initial State";
const setColumnIndex = _.curry((table, index, column, value, state) => {
if (typeof index !== 'number') {
throw new Error(`Tried to setColumnIndex and specified a non-numeric index parameter (1): ${index}, did you mean to call setColumn?`);
}
return "New state"; // state = "Setting up new state here";
});
let result =_.flow([
setColumnIndex('my_wo_table', 1, 'status_id', 2),
setColumnIndex('my_wo_table', 1, 'label_id', 1),
setColumnIndex('my_wo_table', 1, 'date_added', Date.now() / 1000),
])(state);
console.log(result); //=> "New state"
In the above code, if we notice that for setColumnIndex function has 5 parameters when we are calling from flow function, actually passing 4 parameters and with (state) in curry style total 5 parameters.
I am trying to develop a discord bot with nodejs. My question is how do I get a specific data out of a JSON file (for instance, from this json. I want to only specify a single uuid like "59d4c622c7cc459a98c2e947054e2b11" and get the data.
Assuming you have already parsed the JSON into an actual Javascript object named data and given the way the data is currently organized, you would have to search the data.guild.members array to find the object that had the desired uuid property value.
function findDataForUuid(uuid) {
for (let obj of data.guild.members) {
if (obj.uuid === uuid) {
return obj;
}
}
// no match found
return null;
}
let item = findDataForUuid("59d4c622c7cc459a98c2e947054e2b11");
if (item) {
console.log(item); // will show all the properties of the member object
}
Or, using .find() on the array:
function findDataForUuid(uuid) {
return data.guild.members.find(item => {
return item.uuid === uuid;
});
}
The simple soln you can use filter. Best is use reduce.
const data = {
guild: {
_id: "5b2906070cf29ddccd0f203c",
name: "Dulcet",
coins: 122010,
coinsEver: 232010,
created: 1529415175560,
members: [
{
uuid: "59d4c622c7cc459a98c2e947054e2b11",
rank: "MEMBER",
joined: 1529683128302,
questParticipation: 39,
expHistory: {
"2020-02-16": 0,
"2020-02-15": 0,
"2020-02-14": 0,
"2020-02-13": 0,
"2020-02-12": 0,
"2020-02-11": 0,
"2020-02-10": 0
}
}
]
}
};
const members = data.guild.members.filter(
member => member.uuid == "59d4c622c7cc459a98c2e947054e2b11"
);
const firstMember = members[0]
console.log(firstMember)
I need to do this query using adonis:
SELECT * FROM book_unit where book_id = 1 ORDER BY unit desc LIMIT 1 OFFSET 2
So, i do this function:
async procuraProximoSequence(bookId, offSet, maxRecords){
console.log(offSet)
console.log(maxRecords)
const historicoQuery = BookUnit.query()
.where('book_id', bookId)
.orderBy(['unit', 'sequence'], 'asc')
if(offSet !== null){
historicoQuery.offset(offSet)
}
if(maximoRegistros !== null){
historicoQuery.limit(maxRecords)
}
return await historicoQuery.paginate(1, 100)
}
This is the console.log() value of the offSet, maxRecords and the query that knex do:
2 <br>
1 <br>
knex:query select count(*) as "total" from "book_unit" where "book_id" = ? limit ? offset ? undefined +8ms
knex:bindings [ 1, 1, 2 ] undefined +111ms
If i print the result of the query i receive no rows:
VanillaSerializer {
rows: [],
pages: { total: 0, perPage: 100, page: 1, lastPage: 0 },
isOne: false }
The expected row of the query is this image:
It looks like i can’t use .limit() with .paginate()
In my case, i do this correction:
async procuraProximoSequence(bookId, offSet, maximoRegistros){
console.log(bookId, offSet, maximoRegistros)
const historicoQuery = BookUnit.query()
.where('book_id', bookId)
.orderBy(['unit', 'sequence'], 'asc')
if(offSet !== null){
historicoQuery.offset(offSet)
}
if(maximoRegistros !== null){
return await historicoQuery.limit(maximoRegistros).fetch()
}
return await historicoQuery.paginate(1, 100)
}
and now everything works
I am stuck with mongo query. I have a mongo collection structure which i can not modify at this time as it is very large data.
I need to carry out some results from the collection , so tried all ways round to get it.
Here is my collection json schema:-
{
"date": "2017-01-01T00:00:00.000Z",
"bob":"P",
"jacob":"P",
"wilson":"A",
"dev":"SL"
},
{
"date": "2017-01-02T00:00:00.000Z",
"bob":"P",
"jacob":"A",
"wilson":"A",
"dev":"SL"
},
{
"date": "2017-01-03T00:00:00.000Z",
"bob":"P",
"jacob":"P",
"wilson":"A",
"dev":"SL"
},
{
"date": "2017-01-04T00:00:00.000Z",
"shashikant":"P",
"jacob":"P",
"wilson":"SL",
"dev":"SL"
}
....
As output I am looking for below kind of structure:-
from 1st jan 2017 to 30th jan 2017
bob P 17
bob A 2
wilson P 10
dev SL. 1
.....
I am using loopback for my backend but still i can use normal mongodb query to get the output.
Please help
MongoDB allows $unwind only for the arrays. But you could use a simple mapReduce to achieve what you want:
//Define the time frame here
var from = new Date('2015-01-01T00:00:00.000Z');
var to = new Date('2025-01-01T00:00:00.000Z');
db.getCollection('test').mapReduce(function () {
var keys = Object.keys(this);
//If there is no date found on a record, simply skip
if (!this.date) {
return;
}
var date = new Date(this.date);
//Skip the records that do not fit into [form; to] interval
if (!(date >= from && date <= to)) {
return;
}
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
//Emit each combination of key and value
if (key !== 'date' && key !== '_id') {
emit({key: key, value: this[key]}, {count: 1});
}
}
},
function (key, values) {
var reduced = {count: 0};
for (var i = 0; i < values.length; i++) {
var value = values[i];
//Simply counting the combinations here
reduced.count += value.count;
}
return reduced;
},
{
//Passing the dates to mongo
//so 'from' and 'to' will be avail in map, reduce and finalize
scope: {from: from, to: to},
finalize: function (key, reducedValue) {
//Changing the data structure just for a convenience
return {
propertyName: key.key,
propertyValue: key.value,
from: from,
to: to,
count: reducedValue.count
};
},
out: {inline: 1}
}
);
I tested this in Mongo console, but map-reduces are also supported by mongo native Node.js and for mongoose as well.