简体   繁体   中英

pymongo find_one retruning None when used in discord.py command but working fine in terminal

This is the document I'm searching for in my collection.

{'_id': ObjectId('5fef0220e37ad50a37582bc1'), 'nationid': 176311, 'nation': 'Markovia', 'leader': 'Sam Cooper', 'continent': 'Africa', 'war_policy': 'Pirate', 'color': 'beige', 'alliance': 'Arrgh', 'allianceid': 913, 'allianceposition': 3, 'cities': 19, 'infrastructure': 11400, 'offensivewars': 0, 'defensivewars': 
0, 'score': 2283.09, 'rank': 10, 'vacmode': 0, 'minutessinceactive': 50, 'query_nation': 'markovia', 'query_leader': 'sam cooper'}

I have this function that is supposed to enable to me search with a "nationid" , "query_nation" or "query_leader" :

def find_nation(nation):
    if nation.isnumeric():
        nation = int(nation)
        return db.nations.find_one({"nationid":nation})
    else:
        result = db.nations.find_one({"query_nation":nation.lower()})
        if result:
            return result
        else:
            return db.nations.find_one({"query_leader":nation.lower()})

This command works fine when I search for 176311 and markovia but returns None for sam cooper

@client.command()
async def nation(ctx, nation):
    nation_dict_1 = find_nation(nation)
    if nation_dict_1:
        await ctx.send(f'{nation_dict_1["leader"]} of {nation_dict_1["nation"]}')
    else:
        await ctx.send('Could not find an exact match.')

However when I use this in terminal, it works fine with all 3 and prints the document every time. (with sam cooper too)

nation_dict_1 = find_nation(nation)
if nation_dict_1:
    print(nation_dict_1)
else:
    print('Could not find an exact match.')

This is an issue with how your arguments are being passed into the command. sam cooper won't work due to the space in the middle. To fix this, you can use the "consume rest" functionality of the asterisk.

Try this, your rewritten command:

@client.command()
async def nation(ctx, *, nation):
    nation_dict_1 = find_nation(nation)
    if nation_dict_1:
        await ctx.send(f'{nation_dict_1["leader"]} of {nation_dict_1["nation"]}')
    else:
        await ctx.send('Could not find an exact match.')

Your current command would work if you did:
!nation "sam cooper"
But using the asterisk will allow you to enter arguments without the quotations.


References:

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