i'm struggling with mongoDB API, This is my representation of my data :
I'd like to get one list that is stored in userlists correpsonding to his title
Basicaly, i want to fetch only one data that corresponds to a userID and a listTitle
This is my current request and this is not working
exports.getOneMoviesListOfUser = (req, res) => {
const uid = req.params.uid;
const titrelist = req.params.titrelist;
if(uid && titrelist) {
var condition = {"uid": {$regex : new RegExp(uid), $options: "i"}, "userlists.titrelist": {$regex : new RegExp(titrelist), $options: "i"}}
} else {
var condition = {}
}
MoviesDB.find(condition)
.then((data) => {
if (!data)
res
.status(404)
.send({
message:
"Liste de films non trouvée " + uid + "liste = " + titrelist,
});
else res.send(data);
})
.catch((err) => {
res
.status(500)
.send({
message:
"Erreur pendant la récupération de la liste " +
uid +
"liste = " +
titrelist,
});
});
};
Ty if you can help me with this.
Related
I am working on a code that sends a random picture from a subreddit, from the weekly top.
But I receive the following error when I am trying to use the command:
(node:25) UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.
Code:
client.on("message", async message => {
if (message.content.toLowerCase() === "!foto") {
const snekfetch = require('snekfetch');
try {
const {
body
} = await snekfetch
.get('https://www.reddit.com/r/gtavcustoms.json?sort=top&t=week')
.query({
limit: 10
});
const allowed = message.channel.nsfw ? body.data.children : body.data.children.filter(post => !post.data.over_18);
if (!allowed.length) return message.channel.send('Het lijkt erop dat de nieuwe fotos op zijn, probeer het later nog eens!');
const randomnumber = Math.floor(Math.random() * allowed.length)
const embed = new Discord.MessageEmbed()
.setColor(0x00A2E8)
.setTitle(allowed[randomnumber].data.title)
.setDescription("Gepost door: " + allowed[randomnumber].data.author)
.setImage(allowed[randomnumber].data.url)
.addField("Overige informatie:", "Likes: " + allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)
.setFooter("DaddyCoolNL Official Discord Server")
message.channel.send(embed)
} catch (err) {
return console.log(err);
}
}
});
This may be a simple fix, but may not work. What you can try is putting it in backticks.
.addField("Overige informatie:", `Likes: ${allowed[randomnumber].data.ups + " / Comments: " + allowed[randomnumber].data.num_comments)}`
It also may be due to the allowed array not being complete, or something is off with it.
I try to set the member roles, but it doesn't set the permissions.
My index.js file:
var u, s, m;
await bot.users.fetch(message.author.id)
.then(user => { u = user; });
await bot.guilds.fetch('419248578121433100')
.then(guild => { s = guild; });
await s.members.fetch(u)
.then(member => { m = member; });
axios.get('/process')
.then(function (response)
{
var dptos = response.data.dptos;
var attrs = response.data.userAttrs;
var roles = response.data.roles;
if(dptos.length > 0) m.setNickname(dptos[0].position + ' | ' + attrs.name + ' ' + attrs.surname);
else m.setNickname(attrs.name + ' ' + attrs.surname + ' | ' + '123456');
m.roles.set(roles)
.then(function(member)
{
let fd = fs.openSync('log.txt', 'w');
fs.writeSync(fd, JSON.stringify(member.roles.cache));
fs.closeSync(fd);
})
.catch(function(error)
{
let fd = fs.openSync('error.txt', 'w');
fs.writeSync(fd, error);
fs.closeSync(fd);
});
return message.reply('Congrats!');
})
.catch(function (error)
{
return message.reply('error!');
});
}
The axios request works as expected and the data is obtained correctly.
Screenshots:
Bot position
Bot general permissions
UPDATE 1: Nickname permissions
What could be the issue?
I have the following code setup, but it often doesn't find members on my server.
How can I solve this problem?
BOT.on('message', function(message) {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(' ');
const command = args.shift().toLowerCase();
const chan = message.channel;
if (command == "grabreacts" && chan.name == "the-purge") {
var role = message.guild.roles.find(role => role.name === "2019 Purge Survivor");
if (!role) return message.channel.send(`**${message.author.username}**, role not found`);
//console.log(role);
chan.fetchMessage(args)
.then(function(value) {
const react = value.reactions.filter(r => r.emoji == "👍").first();
var reacts = react.count;
react.fetchUsers()
.then(function(users) {
var fetchedMemebers = users.size;
users.map(async user => {
console.log(user.tag);
message.guild.fetchMember(user, false)
.then((memeber) => {
member.addRole(role)
.then((mem) => {
react.remove(user)
.catch((err) => console.log("Cannot remove user: " + user.tag + ". ex: " + ex + "!"));
})
.catch(ex => {
console.log(ex);
});
})
.catch((err) => {
console.log("Cannot find member object for: " + user.tag + "!");
});
});
var assignedusers = role.members.size;
message.reply("Reacts found: " + reacts + "; users fetched: " + fetchedMemebers + "; roles assigned: " + assignedusers);
})
.catch(err => message.reply("Cannot fetch users for react: '" + reacts + "', err: " + err + "!"));
})
.catch(err => message.reply("Cannot fetch message: '" + args + "', err: " + err + "!"));
}
});
It works fine, up until message.guild.fetchMember(user, false), where I fall into the catch block and print many "Cannot find member object for: ******#****!" messages.
I am not getting back any actual exception blocks, and the code worked for the first 62 or 788 reacts. It seems like if the bot doesn't have the user info cached, even using a false in message.guild.fetchMember(user, boolean) doesn't work.
The user object for that member, however is defined. I need the member object to use member.addRole().
Can someone help me figure out how to get this to work, please? Or what I am doing wrong?
I am running node v11.6.0 with "discord.js": "^11.4.2" as a dependency.
Thanks!
I found that the guild object from BOT.guilds.first() has:
members: 656,
memberCount: 2470
So, if I do:
BOT.guilds.first().fetchMembers().then((guild) => {
...
}
That fixes my issue, as the fetchMembers() returns a Promise<Guild> that I can see in the .then() clause, and that Guild object has all members fetched inside of it.
Hope this helps others out!
I am trying to insert the sensor data into a SQL Server database. I have tried all the possible way to insert the incoming data into database, but I failed. I am new to Nodejs and I really have no idea why these errors are occurred during executing process. It would be great if anyone could help me.
Thank you in advance.
The error I get is:
TypeError: Cannot read property 'writeHead' of undefined.
function addData (req, resp, reqBody, data)
{
try {
if (!reqBody) throw new Error("Input not valid");
data = JSON.parse(reqBody);
//reqBody = JSON.parse(data);
if (data) {//add more validations if necessary
var sql = "INSERT INTO arduinoData (Machine, StartTime, EndTime, LengthTime) VALUES ";
sql += util.format("(%s, '%s', %s, %s) ", data.Machine, data.StartTime, data.EndTime, data.LengthTime);
db.executeSql(sql, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
httpMsgs.send200(req, resp);
}
});
}
else {
throw new Error("Input not valid");
}
}
catch (ex) {
httpMsgs.show500(req, resp, ex);
}
};
function sendBackupData()
{
var jsonTable = { "table": [] };
fs.readFile("backup.json", "utf8", function (err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
if (jsonTable.table.length == 0) {
return;
}
for (var index = 0; index < jsonTable.table.length; index++) {
var options = {
url: serverURL,
method: "POST",
form: jsonTable.table.shift()
};
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent backup message!");
} else {
console.log('Error: ' + error);
console.log("CANT'T SEND BACK");
console.log(options.form);
jsonTable.table.push(options.form);
}
});
}
var outputJSON = JSON.stringify(jsonTable);
console.log(outputJSON);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
console.log("Sent backup data!");
});
});
}
function getTime()
{
var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
// Unix Time
var unixTime = Math.floor(date / 1000);
// Check if it is day or night
var isDay;
if (date.getHours() >= 8 & date.getHours() < 16)
{
isDay = true;
}
else
{
isDay = false;
}
return [year + '-' + month + '-' + day, hour + ':' + minute + ':' + second, unixTime, isDay];
}
/*
--- Main Code ---
*/
function vibrationStart()
{
/*
Should get:
- Start time and date the vibration started
- Whether it was day or night
Will send the message, if there is network connection, once complete.
Will store message into a JSON file if there is no network connection.
*/
var jsonTable = { "table": [] };
var startTime = getTime();
console.log(startTime[0] + " " + startTime[1]);
var startData = {
machine: machineName,
start_time: startTime[0] + " " + startTime[1],
day_night: startTime[3],
active: "true"
};
const options = {
url: serverURL,
method: "POST",
form: startData
};
var reqBody = [{
Machine : "",
StartTime : ""
}];
reqBody.push({"Machine" : startData.machine,"StartTime" : startData.start_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent starting message!");
sendBackupData();
addData();
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(startData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
return startTime[2];
}
function vibrationStop(startTimeUnix)
{
var jsonTable = { "table": [] };
var endTime = getTime();
console.log(endTime[0] + " " + endTime[1]);
var endTimeUnix = endTime[2];
var lengthTime = endTimeUnix - startTimeUnix;
console.log("Length time: " + lengthTime);
var endData = {
machine: machineName,
end_time: endTime[0] + " " + endTime[1],
length_time: lengthTime,
active: "false"
};
const options = {
url: serverURL,
method: "POST",
form: endData
};
var reqBody = [{
EndTime : "",
LengthTime :"",
}];
reqBody.push({"EndTime" : endData.end_time,"LengthTime" : endData.length_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent end message!");
sendBackupData();
addData()
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(endData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
}
http.createServer(function (req, resp) {
app.get('/', addData);
}).listen(settings.webPort, function () {
console.log("Started listening at: " + settings.webPort);
});
I have this code...sorry for the messiness I've been at this a while:
loadAvailabilities() {
let promises = [];
let promises2 = [];
let indexi = 0;
//return new Promise((resolve, reject) => {
this.appointments = this.af.list('/appointments', { query: {
orderByChild: 'selected',
limitToFirst: 10
}});
let mapped;
this.subscription2 = this.appointments.subscribe(items => items.forEach(item => {
//promises.push(new Promise((resolve, reject) => {
console.log(item);
let userName = item.$key;
//this.availabilities = [];
for(let x in item) {
let month = x;
console.log(x + " month");
this.appointmentsMonth = this.af.list('/appointments/' + userName + '/' + month);
this.subscription3 = this.appointmentsMonth.subscribe(items => items.forEach(item => {
this.startAtKeyAvail = item.$key;
//console.log(JSON.stringify(item) + " item");
let date = new Date(item.date.day * 1000);
let today = new Date();
console.log(date.getMonth() + "==" + today.getMonth() + "&&" + date.getDate() + "==" + today.getDate());
console.log("IN LOAD AVAILABILITIES *(*((**(*(*(*(*(*(*&^^^^%^%556565656565");
if(date.getMonth() == today.getMonth() && date.getDate() == today.getDate()) {
console.log(" inside the if that checks if its today");
console.log(item.reserved.appointment + " *************appointment");
//let counter = 0;
//mapped = item.reserved.appointment.map((r) => {
//item.reserved.appointment.forEach((r, index) => {
for(let r of item.reserved.appointment) {
promises.push(new Promise((resolve, reject) => {
if(r.selected == true) {
//this.renderer.setElementStyle(this.noavail.nativeElement, 'display', 'none');
let storageRef = firebase.storage().ref().child('/settings/' + userName + '/profilepicture.png');
let obj = {'pic':"", 'salon': userName, 'time': r.time};
storageRef.getDownloadURL().then(url => {
console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
obj.pic = url;
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
}).catch((e) => {
console.log("in caught url !!!!!!!$$$$$$$!!");
obj.pic = 'assets/blankprof.png';
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
});
}
}))
}
}
}))
}
}))
//}));
Promise.all(promises).then(() => {
console.log("in load availabilities ......... ")
console.log(JSON.stringify(this.availabilities));
this.availabilities.sort(function(a,b) {
return Date.parse('01/01/2013 '+a.time) - Date.parse('01/01/2013 '+b.time);
});
console.log('*****previous******');
console.log(JSON.stringify(this.availabilities));
console.log('*****sorted********');
for(let i of this.availabilities) {
console.log(i.time + " this is itime");
let date = new Date('01/01/2013 ' + i.time);
console.log(date + " this is date in idate");
let str = date.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
console.log(str);
i.time = str;
}
});
//}))
//})
}
I can tell from the log messages that the storageRef.getDownloadURL() function happens close to the end of when my page loads...this is where the objects actually get pushed to this.availabilities (eventually used to populate a list). The code in the Promise.all .then() actually fires before anything gets pushed to this.availabilities so when the sorting happens it is an empty array and nothing gets sorted.
I used a promise inside each forEach loop. I pushed all the promises to the same array and used Promise.all(array).then(...) how it is being used above - and the promises did their job - the array is sorted because everything is happening asynchronously.