Cursor.next() never resolves using Mongoose (4.13.19) - javascript

I'm attempting to use a cursor:
const cursor = Thing.find({}).cursor();
cursor.next().then((a,b) => { console.log(a); console.log(b); })
But this never resolves; it just sits there. There doesn't seem to be a cursor.exec() or anything like that. cursor.close() even throws TypeError: Cannot read property 'close' of null.
All the documentation I can find ignores this and just goes about its example, thus implying I don't need it. But I quite obviously do, as it doesn't actually load any documents from Mongo.
This is on a legacy project and I'm unable to change the version of Mongoose. Node is 8.15.0, MongoDB is 3.2, and both are in a similar boat.

Ok, look, I'm going to own up to my stupidity here and admit that I hadn't actually connected to mongo before attempting to load the data. I'm also going to leave this question up as a combination of reference and penance.
Though to be fair I have no idea why mongoose wouldn't tell me it's not connected instead of blocking on a nonexistent connection. But I still should have known.

Related

discord.js - Receiving error when trying to retrieve userID of .repliedUser

Here’s the situation:
In my server I have a bot (not mine) that replies to specific user actions with a message containing an embed that has the word “Done!” in the description. I want to set it up so that once this bot sends the “Done!” message the user it replied to receives a role.
Today being the first day I’ve ever used javascript means I’m not surprised I’ve encountered an error, however I simply could not figure out how to fix it. I tried working around the error by attempting to achieve my intended result by different methods, but I cannot find an actual alternative so I’ve ended up back at the error.
The code that I’m experiencing the error with is this:
client.on('messageCreate', (message) => {
let role = message.guild.roles.cache.find(r => r.id === "1001628984829816952");
let member = message.mentions.repliedUser();
let done = "done!"
if (done(w => message.embeds.description.toLowerCase().includes(w))) {
member.roles.add(role);
}
});
and the error I'm receiving is this:
let member = message.mentions.repliedUser();
^
TypeError: message.mentions.repliedUser is not a function
I'm a bit confused as I was sure .repliedUser is valid, although this may be my absolute inexperience with javascript shining through.
On a side note, I believe I have the necessary intents enabled:
import { Client, GatewayIntentBits } from 'discord.js';
import dotenv from 'dotenv'
dotenv.config()
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
so those shouldn't be a problem.
What I've tried by means of my own intuitive bumbling is replacing message.mentions.repliedUser() with message.mentions.repliedUser.get() since I've seen .get used at the end a bit like that and it sounds about right (I'm laughing at my own explanation here, please bear with me...), however I receive a different error with that in place:
let member = message.mentions.repliedUser.get();
^
TypeError: Cannot read properties of null (reading 'get')
I'm not surprised by this result, though, (even if I don't fully understand what it's trying to tell me...) since .repliedUser isn't recognised anyways.
I'm not really sure where to go from here, especially since there seems to be no mention of .repliedUser anywhere on the internet except for the discord.js docs, and also because much of the general help for discord.js is still aimed at v13, whereas I'm running v14, and the two are not compatible.
Any and all help is much appreciated, and I'm sorry if this question is stupid and the answer to it is incredibly rudimentary, which I'm guessing it is. I also hope that my code is readable; it seems to mostly work, except for the error, but it is also mostly patchwork so it could just be some nonsense that's pretending to work.
(At least this has convinced me to get into javascript properly, even if only for my own peace of mind.)
Looking at the documentation, message.mentions.repliedUser is of type ?User. You are expecting it to be of type (...) => ?User, which it isn't.
Simple fix, just replace .repliecUser() with .repliedUser.

Slash Commands - Discord.js

I am getting an error when I am trying to run:
(node:9164) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'applications' of undefined
Here is my code:
const discord = require('discord.js');
const client = new discord.Client();
const guildId = '820368493017825333';
client.on('ready', async () => {
console.log('ready');
const commands = await client.api.
applications(client.user.id)
.guilds(guildId)
.commands.get();
console.log(commands);
});
client.login(require(`./config.json`).Token);
Issues With the Accepted Answer
The accepted answer is incorrect in several ways. I'll walk through the inaccuracies in that answer and highlight the more likely causes of this problem, for the sake of anyone that may stumble upon this question in the future (and would've been misled by the accepted answer into believing that Slash Commands cannot be implemented in discord.js).
Well, the answer is pretty simple here. According to Discord.js docs, Class Client doesn't have api property. That's why you have the undefined error.
Incorrect. The Client class does have an api property. Or rather, it inherits the api property from the BaseClient class that it extends. This can be found in the source code of BaseClient. It is true that this is not documented in the discord.js docs. That is intentional, as the api property is intended to be a private property, more for discord.js' own use than for general use. You may notice in the source code that the property is annotated with #private, which usually indicates that it will not appear in the docs. There are many such private properties and methods that exist in discord.js classes, which are undocumented but are usable in your own code.
It seems like the tutorial that you are looking at is a bit outdated, or probably the tutor adds this property manually because Discord.js have relevant classes, like Application and ClientApplication but I still don't see an api property there as well.
The tutorial that the OP was going off of was actually more up-to-date than the tutorials posted and used by the accepted answer. The Application and ClientApplication classes are not at all relevant, as neither can access Slash Commands. Nor did hundreds of different tutorials each implement their own api property that all work in exactly the same way; they were all using the api property included in the latest versions of discord.js.
If you want to implement commands to your Discord bot with slash support, just add the following code, after ready stage.
The accepted answer misunderstood what 'Slash Commands' are, and provided code simply for creating a command with a slash for a prefix. That is not what the Slash Command system is. Slash Commands allow you to do things such as documenting, autocompleting, and validating commands and command arguments that users are typing in, in real-time while they are entering their input.
Not it shouldn't. Actually, the Discord.js lib is updated more often, the [YouTube] creators do it with their videos. I have already placed in my answer, a relevant guide made by the Discord.js community.
Yes it should. Hundreds of tutorials used the same code as each other, containing the api property, in instructing developers on how to work with Slash Commands in unmodified discord.js. I am not sure what exactly was meant by this comment.
If you look at the actual source code of discord.js, you'll find that the latest versions use the client's api property several times internally, usually in methods that directly query the Discord API for information (such as .fetch() methods). If the api property is undefined and you are using the latest version of discord.js, then much of your bot would not be working properly. So the latest client class not having an api property is not the main issue, which leads us to what the main issue really is.
So What Is the Real Issue?
There truly isn't enough context provided in the question to know for sure what exactly was causing the issue in the question. However, we can narrow the cause down to a few potential suspects, especially given the information aforementioned. Double check these to ensure they are not causing your problem:
Discord.js version. The api property does not exist for versions older than v12. Make sure you are using the latest version of discord.js. This is most likely the cause of the issue.
Missing access. You need to give your bot the application.commands scope when generating its invite link, otherwise you cannot interact with or create Slash Commands. This shouldn't really cause the api property to be undefined and should give you a different error, but it's worth double-checking.
If working with Slash Commands in simple discord.js is still not working for you even after double-checking both of these potential issues, you may want to consider an alternate (and somewhat simpler) approach to implementing Slash Commands: the discord-slash-commands-client module.
You would initialize this module like so:
const interactions = require("discord-slash-commands-client");
const iclient = new interactions.Client(
"you unique bot token",
"your bots user id"
);
Then to get a list of all existing Slash Commands, as the code in this question is attempting to do, all you would need to do with this module is:
let commands = await iclient.getCommands();
A single, clean line. As simple as it gets. The only downside to this alternate approach is that this module may not stay up-to-date as reliably as discord.js itself does. However, it would certainly be helpful if you are not able to figure out how to get Slash Commands working in discord.js itself.
If you need more help on this or want to see a more complete implementation of either approach, this question has several good, working examples on how to get Slash Commands code working properly on your bot.
This answer is a outdated!
When it was accepted Discord haven't introduced truly /slash commands. So use the answer below, if you want to integrate or migrate to newest version of Discord.js
Well, the answer is pretty simple here. According to Discord.js docs, Class Client doesn't have api property. That's why you have the undefined error.
It seems like the tutorial that you are looking at is a bit outdated, or probably the tutor adds this property manually because Discord.js have relevant classes, like Application and ClientApplication but I still don't see an api property there as well.
If you are looking for a good guide, I might recommend you this one from the official Discord recommendation page.
If you want to implement commands to your Discord bot with slash support, just add the following code, after ready stage.
const prefix = '/'
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('Pong.');
}
})

Is there any way to get a dmChannel id just from the user object? (discord.js v11)

If I'm trying to figure out how to get the id of a dmChannel, with only the user's object so I can bulk delete in user's dms, how would I do this? The code I have so far is:
let dm = client.users.get('123481923481234').createDM()
the error I got was:
TypeError: Cannot read property 'createDM' of undefined
I also tried getting the user from a guild members list, here's the code:
let dms = client.guilds.get('783871449466142750').then(guild=>{
guild.members.get('432325763753050122').createDM().channel.id
})
This got the error:
TypeError: client.guilds.get(...).then is not a function
Anyone know whats wrong? Any help would be appreciated!
Did you try looking at the discord.js docs? That's the website where discord.js documents exactly how to use every method and property available in discord.js, and you would be able to solve every issue you experienced in this question in seconds by simply looking at the documentation. The docs, being the place that tells you how to use everything in discord.js, should've been the first place you looked for answers; StackOverflow is more of a last resort situation that you come to when you are completely stuck, and this is certainly not one of those situations.
In the first issue you are having, the error tells you everything: Cannot read property 'createDM' of undefined. What does that tell us? It tells us that client.users.get('123481923481234') is undefined, or in other words, the user with that ID cannot be found in your bot's cache (client.users represents the bot's user cache). Either you used an incorrect ID, or the bot's cache simply hasn't been updated to include that specific user. If you want to get that user even if they are not in your bot's cache, you can directly ask the Discord API for that information using client.fetchUser(). This method returns a Promise, so you'll want to use .then() to access its asynchronous data. (.createDM() is also a Promise so you'll need a .then() to access the created DMChannel as well). Here's what it should look like:
client.fetchUser('123481923481234', true).then(user => {
user.createDM().then(dmchannel => {
//Now do whatever you want with the ID
var channelID = dmchannel.id;
});
})
As for the second thing you tried, that's just completely wrong. I don't know how you created that code, but you definitely didn't look at the docs to see if you were doing it right; it honestly looks like you just guessed without checking how it actually works. First of all client.guilds.get() does not return a Promise, so you don't use .then() on it. You should already know that, since you didn't use .then() on the .get() in the first thing you tried. Second, as previously mentioned, .createDM() does return a Promise and therefore does require a .then() which you did not use in your attempt. You ended up doing the opposite of what you needed to do in each of the two above parts of this second attempt. Third, the Promise of .createDM() provides you with a DMChannel object and not a DM object, so you're attempting to do DMChannel.channel.id when you should just be doing DMChannel.id. Fixing all of that might get this second attempt to work, but it might still not work due to the reason your first attempt did not work. If that's the case, you would just need to switch all of your uses of .get() in this second attempt to its fetching equivalent, which you can find easily on the docs. For the sake of a simple, readable answer, I am not going to use the fetching equivalents in this second answer. So here's how your second attempt should look:
var guild = client.guilds.get('783871449466142750');
guild.members.get('432325763753050122').createDM().then(dmchannel => {
//Now do whatever you want with the ID
var channelID = dmchannel.id;
});
Here are the links to the pages in the documentation that explain how to use the methods and objects in these two answers. Please go to these pages and look at how the methods work, and refer to the documentation in the future when you're not sure how something works, when you want to figure out how to do something, or when something you've developed in discord.js is not working properly. Most of the methods on the docs come with provided, understandable examples along with documentation of all available options and parameters. Only ask a question here if it cannot be answered by the docs.
https://discord.js.org/#/docs/main/v11/class/Client?scrollTo=fetchUser
https://discord.js.org/#/docs/main/v11/class/User?scrollTo=createDM
https://discord.js.org/#/docs/main/v11/class/DMChannel
https://discord.js.org/#/docs/collection/master/class/Collection?scrollTo=get

Node: Require Not Working for One Module

Solution Found: Turns out the problem was a "circular" dependency. For anyone who else might encounter this problem, I found the answer here: Require returns an empty object
First time asking a question. I'm still learning, and I thought I knew what I was doing here, but I can't make sense of this.
I am working on a Node project with MongoDB/Mongoose. At the top of my file, I have:
const {Institution} = require('./institution');
const {Student} = require('./student');
When I run my program and use Institution.findOne() it errors and says cannot read property findOne of undefined. I use the Institution model in several other files and they all work fine.
The model is required in several steps before this one and always works fine. Since the model works in other cases, I would think the exports are working just fine.
const Institution = database.model('Institution', InstitutionSchema);
module.exports = {
Institution,
InstitutionSchema
};
Both institution.js and student.js are in the same folder as this file.
When I do console.log(Student), it returns the huge Mongoose object.
When I do console.log(Institution), it returns undefined.
If I console.log(Institution) from another module where it is working, it returns the Mongoose object.
The Institution collection is in my database and I can view the content in Robomongo viewer.
Am I missing something that I just can't see?
Thanks in advance for any help.

Backbone.js: "Remove nonexistent models if appropriate" fails

I don't know how to ask this but I'll try to be as specific and as comprehensible as I can.
I am working on application based on Backbone and Marionette which is fetching data from back-end api server. We have got some input field with auto-completion which works fine but just first time. Second time I'd type something the auto-complete crashes. Ehm, not exactly the auto-complete but the backbone.js itself. I am getting this error:
Uncaught TypeError: Cannot read property 'cid' of undefined backbone.js:716
_.extend.set backbone.js:716
Backbone.Collection.set backbone-relational.js:1851
_.extend.fetch.options.success backbone.js:860
Backbone.Paginator.Paginator.requestPager.Backbone.Collection.extend.sync.queryOptions.success backbone.paginator.js:840
jQuery.Callbacks.fire jquery.js:3073
jQuery.Callbacks.self.fireWith jquery.js:3185
done jquery.js:8251
jQuery.ajaxTransport.send.callback jquery.js:8598
Probably between two calls to retrieving data from api server I somewhere forget to "reset" retrieved model collection - I am very new to Backbone development so it is really possible.
I am sorry for not providing code samples but I want you to ask also something else - it is about how Backbone algorithm for "Remove nonexistent models if appropriate" works - can be found here https://github.com/jashkenas/backbone/blob/master/backbone.js#L734
I was curious why my code crashes so I started to debugging backbone script itself (maybe not so good idea as it looks but I found out something interesting). In the provided link above you can see that backbone is iterating through models and deletes everything that is not needed. Its O.K. but I think that there is bug because backbone tries to iterate N times where N is this.length instead of this.models.length. In my case this two lengths are different. In my models I have for example 2 models but backbone tries to iterate 4 times because the value of this.length is 4.
Could please anybody explain to me why are these values different? I assume that this.length should be updated any time the length of this.models changes but in my case this is not happening.
Any ideas?
If you're doing a collection.fetch() somewhere try replacing it with collection.fetch({reset: true}) - it worked for me.

Categories

Resources