I don't how to do it, please help the kidding develop (T_T).
It shows "undefined" when I'm executing:
router.get("/filter-report/", verifyToken, (req, res) => {
queries.report_table
.Filter_leave()
.then(requests => {
let leavetype = req.query.request_category;
let depart = req.query.department;
let fname = req.query.first_name;
let obj = {filter: leavetype + ''+ depart+''+fname}
console.log(obj);
res.json(obj);
});
});
The URL should look like /filter-report?request_category=category&department=dev&first_name=test
but I think the error is in line 2, queries is not defined/initialized
Adding to Vinil's answer. Queries can be accessed from req. It is an Object. So if your url looks like this:
/filter-report?request_category=category&department=dev&first_name=test
Then your query object will be looking like this:
{
request_category: category,
department: dev,
first_name: test
}
And you can access that query as usual using req.query.request_category, etc.
Related
I'm quite new to Javascript, normally a Python person. I've looked at some other answers but my embed does not add the fields as expected. The embed itself is sent.
My Discord bot follows the guide provided by the devs (primary file, slash commands, command files). I am trying to loop through the entries in an SQLite query and add them as fields.
My command file is below.
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js')
const sqlite = require('sqlite3').verbose();
module.exports = {
data: new SlashCommandBuilder()
.setName('rank')
.setDescription('Rank all points.'),
async execute(interaction) {
const rankEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Rank Board')
let db = new sqlite.Database('./databases/ranktest.db', sqlite.OPEN_READWRITE);
let queryall = 'SELECT name, points FROM pointstable ORDER BY points DESC'
db.all(queryall, [], (err, rows) => {
if (err) {
console.log('There was an error');
} else {
rows.forEach((row) => {
console.log(row.name, row.points)
rankEmbed.addField('\u200b', `${row.name}: ${row.points}`, true);
});
}
})
return interaction.reply({embeds: [ rankEmbed ] });
}
}
I would also like to convert row.name - held as Discord IDs - to usernames i.e. MYNAME#0001. How do I do this by interaction? I was able to obtain the User ID in another command by using interaction.member.id, but in this case I need to grab them from the guild. In Python I did this with await client.fetch_user but in this case the error await is only valid in async functions and the top level bodies of modules is thrown.
Thanks.
OK I've solved the first aspect, I had the return interaction.reply in the wrong place.
Relevant snippet:
rows.forEach((row) => {
console.log(row.name, row.points)
rankEmbed.addField('\u200b', `${row.name}: ${row.points}`, false);
})
return interaction.reply({embeds: [rankEmbed ]} );
Would still appreciate an answer to the converting row.name (user ID) to user name via fetch.
I've solved the second aspect also. Add the below into the loop.
rows.forEach((row) => {
let client = interaction.client
const uname = client.users.cache.get(row.name);
rankEmbed.addField('\u200b', `${uname}: ${row.points}`, false);
I've been trying to format a URL POST with objects in my array as they're required to post to my REST API. I'm forced to use an archaic API POST system from a vendor and have been trying to hack together a solution.
Basically the JSON looks similar to:
{"api_key": "12234",
"server_id:"qwp2222",
"recipients": [
{"email":"john#doe.com",
"name": "john doe"}]
}
I am trying to format the Array'd key-value pairs as part of the URL so it would post to the endpoint without much fanfare.
I have the rest of the URL together without issue, it is just the recipients' array that is the problem.
How should I write the POST URL in order to make sure that I can post the array of objects correctly?
I appreciate all the help in advance!
Does not work here, but this code will make linear structure from your JSON, create form from and submit to itself.
If you run it on local or anywhere else and add f.action = 'your get or post page', it will send data properly.
var data = {
api_key: '12234',
server_id: 'qwp2222',
recipients: [{
email: 'john#doe.com',
name: 'john doe'
}]
};
function collectItems(res, json) {
for (var a in json) {
if (json[a].constructor === Array ||
json[a].constructor === Object) {
collectItems(res, json[a]);
} else {
res.push([a, json[a]]);
}
}
}
var all = [];
collectItems(all, data);
var f = document.createElement('FORM');
f.method = 'post';
// default get: ...?api_key=12234&server_id=qwp2222&email=john#doe.com&name=john+doe
for (var e in all) {
var i = document.createElement('INPUT');
i.name = all[e][0];
i.value = all[e][1];
i.type = 'hidden'; // do not show values sent
f.appendChild(i);
}
if (location.search) {
alert("Submit result:" & location.href);
} else {
document.body.appendChild(f);
f.submit();
}
I want to assign snap.val() to this.Productslike this.Products= snap.val(); but this.Products is undefined in that scope.
Products: FirebaseListObservable<any>;
constructor(){
}
ionViewDidLoad(){
this.angularFire.database.list('/Products').$ref.orderByChild('uid')
.equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133').on('child_added', function(snap){
console.log(snap.val().name);
//this.Products= snap.val();
});
}
I tried the following code when snap is returned ,but I receive this message -- No index defined for uid:
snap.forEach(SnapShot=>{
console.log(SnapShot.val().name)
My Firebase database:
"Products" : {
"-Kbx0i-TFeTyRbNZAZ_8" : {
"category" : "1",
"detail" : "xxxxx details",
"name" : "xxxxx",
"uid" : "NW1Kq4WB7ReUz2BNknYWML9nF133"
}
Please help. Thanks.
The directly answer the question you asked, you can use an ES6 arrow function:
let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
.equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133');
query.on('child_added', (snap) => this.Products= snap.val());
Or for ES5 compatibility, declare this as a variable:
let self = this;
let query = this.angularFire.database.list('/Products').$ref.orderByChild('uid')
.equalTo('NW1Kq4WB7ReUz2BNknYWML9nF133');
query.on('child_added', function(snap) {
self.Products= snap.val();
});
But in reality, this is an XY problem and you don't want what you think you want here.
What you've done is reimplement the list yourself, and defeat the entire purpose of AngularFire2, which handles all this synchronization on your behalf.
Additionally, you've mis-used child_added by assigning each record you get back (you get an array of results, not exactly one) to this.products, when you probably wanted to set this.products = [] and then use this.products.push(snap.val()) for each child_added invocation.
So what you really want here, is to use AngularFire's built-in queries and avoid this entire mess :)
this.products = af.database.list('/Products', {
query: {
orderByChild: 'uid',
equalTo: 'NW1Kq4WB7ReUz2BNknYWML9nF133'
}
});
I did it in this way:
import firebase from "firebase";
const firebaseConfig = {
your firebaseConfig...
};
let app = firebase.initializeApp(firebaseConfig);
let database = firebase.database();
export async function readFromFirebase(userId, key) {
const ref = database.ref("users/" + userId + "/" + key);
const snapshot = await ref.once("value");
return snapshot.val();
}
async function main() {
console.log(await readFromFirebase(109512127, "userName"));
}
main();
I am quite new to firebase and i am trying to retrieve particular data. and getting this error,
Please help me with this.
My code looks like this
var t1= this.password.value;
var user_id = this.state.comments[2];
firebase.database().ref(user_id).orderByChild("Password").equalTo(t1).on("child_added", (snapshot) => {
var datas1 = []
snapshot.forEach((data1) =>
{
datas1.push( {
username: data1.val().Username,
password: data1.val().Password,
});
});
this.setState ({
datas1: datas1,
});
});
console.log(this.state.datas1);
even the array datas1 is coming empty.
I am using mongoose ODM and have a schema which looks like this:
var banSchema = new Schema({
userid: { type: String, required: true, unique: true },
name: String,
groupid: String,
reason: String,
timestamp: Date
});
I want to output every single user id from all documents in the collection. I am using this query to obtain the userid objects. However I cannot seem to get the full list automatically. I have to manually enter the object number as seeen below:
bot.onText(/\/sync/i, function (msg) {
var fromId = msg.from.id;
var chatId = msg.chat.id;
if (fromId == config.sudo) {
console.log('Sudo Confirmed And Authorized!');
Ban.find({}, function (err, obj) {
console.log(obj[0].userid); // Returns A Single ID
console.log(obj[1].toObject().userid); // Returns a different ID
bot.sendMessage(chatId, obj[1].toObject().useridid);
});
} else {
console.log('Someone Is Trying To Act Like Sudo! *sigh*');
bot.sendMessage(chatId, 'You Are Not A Mod!');
}
});
This however does not return a full list of id's as I want. How could I solve this issue?
The code above is for a telegram bot which on a /sync command it should return a message with all ids from the collection.
Telegram bot API Limits
Due to the API limits, the entire output should be in a single message.
var query = Ban.find({}).select({
"userid": 1,
//Add more column fields here
"_id": 0 //Ensures _id is not displayed
});
var arr = [];
query.exec(function (err, results) {
if (err) throw err;
results.forEach(function (result) {
arr.push(result.userid);
// Add more column fields here;
});
var fixedJoin =arr.join("\n");
console.log(fixed);
bot.sendMessage(chatId, 'List\n\n' + fixedJoin);
});
The easiest way to get all values of a particular field across all docs in the collection is to use distinct:
Ban.distinct('userid', function (err, userids) {
// userids is an array containing all userid values in the collection.
// string.join into a single string for the message.
bot.sendMessage(chatId, 'USER IDs\n\n' + userids.join('\n'));
});
Use this syntax
Ban.find({}).
select('userid').
exec(function(err, result) {
//result is array of userid of all document
});
You can use this syntax:
Ban.find({}, 'userid', function(err, users) {
users.forEach(function(user) {
console.log(user);
bot.sendMessage(chatId, 'users \n' + user);
});
})