简体   繁体   中英

get a specific field from mongo db with javascript, discord.js

I made a blacklist command to blacklist users from my bot. I wanted it to message the user the reason why they were blacklisted but I can't figure out how to do that.

        let profile = await Blacklist.findOne({
            userID: message.author.id,
        });
        let reasons = await Blacklist.findOne({
            userID: profile,
            reason: reasons
        })
        if (profile) return message.reply(`ur banned from using this bot lmao, reason: ${reasons}`)

however this outputs an error of

ReferenceError: Cannot access 'reasons' before initialization

this is what i have in mongoDB这就是我在 mongoDB 中所拥有的

It looks like you're fetching the same document from MongoDB in both of your findOne() calls, because of how you simply use the profile that you just fetched in the first call to fetch a document in the second call. Shouldn't this work?

let profile = await Blacklist.findOne({
    userID: message.author.id,
});
if (profile) return message.reply(`you're banned for reason: ${profile.reasons}`)

And the reason you're getting that Cannot access 'reasons' before initialization error is because in the second findOne call you set a new variable reasons to the return value of the function, but you pass the reasons variable into the expression on the right side, which is still executing, so your left side reasons variable has not been initialized. But that statement didn't make sense anyway; you should be able to just delete it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM