This is a problem with my mongoose model.find code at the bottom
Pasted below is my node.js code using mongoose to interact with MongoDB. For some reason, when I run it I get the following result:
Starting...
(node:7863) UnhandledPromiseRejectionWarning: MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments
at Collection.find (/Users/justing/Documents/WebDev/FruitsProject/node_modules/mongodb/lib/collection.js:238:19)
at NativeCollection.<computed> [as find] (/Users/justing/Documents/WebDev/FruitsProject/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:191:33)
at NativeCollection.Collection.doQueue (/Users/justing/Documents/WebDev/FruitsProject/node_modules/mongoose/lib/collection.js:135:23)
at /Users/justing/Documents/WebDev/FruitsProject/node_modules/mongoose/lib/collection.js:82:24
at processTicksAndRejections (internal/process/task_queues.js:77:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7863) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7863) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
What I should see is the name attribute of an instance of the Fruit model. I've tried substituting in {} for argument #1, as per documentation but I can't seem to get the desired result, which is just to console.log them.
const mongoose = require("mongoose");
console.log("Starting...");
mongoose.connect("mongodb://localhost:27017/fruitsDB", {useNewUrlParser:true});
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model("Fruit", fruitSchema);
const fruit = new Fruit ({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit."
});
fruit.save();
Fruit.find({},function(err,fruits){
if (err) {
console.log(err);
} else {
console.log(fruits);
fruits.forEach(function(fruit){
console.log(fruit.name);
});
}
});
I think there is no error in your code, but if this code runs multiple times, you should define your Fruit Schema in another file because you cannot redefine the same schema in running time.
Related
I'm using tesseract within my node app. The first time the program runs fine.
In this example, foo() repeats it self. From the first repition on, an error is returned (shown below the code)
Could you give me a hint what I have done wrong which doesn't allow this to run a second time? I have tried to add try & catch, but it only led to more errors
const { createWorker } = require('tesseract.js');
const worker = createWorker();
function foo() {
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
await worker.setParameters({
tessedit_char_whitelist: '123456789'
// preserve_interword_spaces: '0',
});
const { data: { text } } = await worker.recognize('Download.png');
console.log(text);
await worker.terminate();
})();
setTimeout(foo, 10000);
}
foo();
Error message:
(node:13988) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of null
at module.exports (\\node_modules\tesseract.js\src\worker\node\send.js:9:10)
at \\node_modules\tesseract.js\src\createWorker.js:47:7
at new Promise (<anonymous>)
at startJob (\\node_modules\tesseract.js\src\createWorker.js:43:5)
at Object.load (\\node_modules\tesseract.js\src\createWorker.js:57:5)
at \\tesseract3.js:28:18
at Timeout.myFetch [as _onTimeout] (\\tesseract3.js:38:5)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13988) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:13988) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13988) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of null
I'm making a discord bot but when I create a ping command it says the following:
(node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
embeds[0].footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
at RequestHandler.execute (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async callback (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\commands\misc\ping.js:15:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:37584) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:37584) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My code for ping.js is:
const { MessageEmbed } = require("discord.js")
module.exports = {
commands: ["ping", 'pong'],
expectedArgs: "",
permissionError: '',
minArgs: 0,
maxArgs: null,
callback: async(message, args, text, client) => {
let pinging = new MessageEmbed()
.setTitle('Pinging....')
.setColor("RED")
.setFooter(client.user.avatarURL(), client.user.username)
const msg = await message.channel.send(pinging)
let embed = new MessageEmbed()
.setTitle('Pong! 🏓')
.addField("Api Latency", `${Math.floor(message.createdTimestamp - message.createdTimestamp)}ms`)
.addField("Latency", `${Math.floor(client.ws.ping)}ms`)
.setColor("LIGHT_GREEN")
.setFooter(client.user.avatarURL(), client.user.username)
.setTimestamp()
msg.edit(embed)
}
}
Can someone help me with this? I tried doing message.client.user.avatarURL() and also the displayAvatarURL() function but it keeps giving this error
Your logs say
embed.footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https'). embeds[0].footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
Which seems to indicate the url provided for your icon is incorrect (and does not start with http or https which is required).
I assume this is client.user.avatarURL() which is incorrect, try to replace it with a hard coded picture link and see if it helps. You may have an incorrect value in avatarURL...
router.get('/:id', async (req, res) => {
const course = await Course.findById(req.params.id);
if (!course) {
return res.status(400).send(`course id is invaild`);
}
res.send(course);
});
As you guys can see, this is a very simple route function.
It works fine if it got the right id but once I gave it the wrong id it throws this error on my console
GET /api/courses/600f4aab118a6c5ef60fb5f7 200 75 - 20.069 ms
(node:32606) UnhandledPromiseRejectionWarning: CastError: Cast to
ObjectId failed for value "600f4aab118a6c5ef60fb5f7a" at path "_id"
for model "Course"
at model.Query.exec (/home/hesham/Desktop/test-express/node_modules/mongoose/lib/query.js:4358:21)
at model.Query.Query.then (/home/hesham/Desktop/test-express/node_modules/mongoose/lib/query.js:4452:15)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created) (node:32606)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled
with .catch().
To terminate the node process on unhandled promise
rejection, use the CLI flag `--unhandled-rejections=strict` (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) (node:32606) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.
everytime I am trying to do like: !help command , if the command doesn't have any aliases, it gives me that error in the console, I tried the following method which if there is no aliases for the specific command, it should return 'None' , here's the code:
let command = helpArgs[0]
if(helpArgs[0]){
if(bot.commands.has(command)) {
command = bot.commands.get(command)
const embed = new Discord.MessageEmbed()
.setTitle(`${command.config.name}`)
.addField('Name', `${command.config.name}`)
.addField('Description', `${command.config.description}`)
.addField('Usage', `${command.config.usage}`)
.addField('Aliases', `${command.config.aliases !== undefined ? command.config.aliases : 'None'}`)
message.channel.send(embed)
And here is the error:
7:14 GMT+0300 (Eastern European Summer Time)
(node:11744) UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.
at Function.normalizeField (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:425:23)
at C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:445:14
at Array.map (<anonymous>)
at Function.normalizeFields (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:444:8)
at MessageEmbed.addFields (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:259:42)
at MessageEmbed.addField (C:\Users\\OneDrive\Documents\GitHub\Fergus\node_modules\discord.js\src\structures\MessageEmbed.js:250:17)
at Object.module.exports.run (C:\Users\\OneDrive\Documents\GitHub\Fergus\commands\Information\help.js:115:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11744) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:11744) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
The error is at .addField('Aliases', ${command.config.aliases !== undefined ? command.config.aliases : 'None'}) , I checked each field.
I think the error may be, that the method you used in this field causes an error and because of this, the field is empty. To list the aliases in a string you can try the following method.
let aliases = command.config.aliases.toString();
if (aliases == "") {
aliases = "None";
}
.addField('Aliases', `${aliases}`)
With this method, you create a String from the aliases array of your command config. Then you look if there aren't any aliases. If yes the String is "None". After this, you need to replace your method in the embed with the variable aliases.
It seems like command.config.aliases is indeed empty, even though it is not undefined. You should modify the check. I do not know what the aliases field contains, so I cannot say what the check should be.
I'm making a discord bot and if I type $join into chat, I want the bot to join the voice channel that I'm in, and play a random sound.
case"join":
message.delete( {timeout: 5000})
const voiceChannel = message.member.voice.channel
if(voiceChannel) {
const connection = await voiceChannel.join()
const soundFile = fs.readFileSync("./sounds/")
const randFiles = soundFile[Math.floor(Math.random() * randFiles.length)]
const dispatcher = connection.play(randFiles)
} else {
message.reply("you need to be in a voice channel!").then(message => message.delete( {timeout: 5000}))
}
break;
I'm getting this error:
(node:13932) UnhandledPromiseRejectionWarning: Error: EISDIR: illegal operation on a directory, read
at Object.readSync (fs.js:524:3)
at tryReadSync (fs.js:349:20)
at Object.readFileSync (fs.js:386:19)
at Client.<anonymous> (C:\Users\PC\Desktop\doge_bot\doge-bot.js:124:38)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13932) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13932) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not
handled will terminate the Node.js process with a non-zero exit code.
Have you read the documentation for readFileSync()? The only OS that readFileSync() successfully returns data on a directory path is on FreeBSD.
Instead, what it appears you're trying to do is grab a list of the files at a directory path; for this you could use fs.readdirSync():
const soundFile = fs.readdirSync("./sounds/")
fs.readFileSync("./sounds/") is for reading the contents of a file.
You're probably looking for fs.readdirSync("./sounds/") which gives you an array of files in a directory.