Home > database >  How can i check if the value for "_id" field exists and how to read, write, update and del
How can i check if the value for "_id" field exists and how to read, write, update and del

Time:02-16

I have a discord bot for dealing with user notes. So the bot basically stores a string as a note in a list inside the database. The notes are user specific. So i tried setting ctx.author.id as the value for "_id" field and then checking if the user id of the person using the command is equal to the value of "_id" in any document in the database. But it does not work.

Here is my code for the command:

@client.command()
async def makenotes(ctx, *, args):
    try:
        if (len(db.NoteBoyNotes.find_one({'_id':ctx.author.id})) == 0):
            NotesUpdateDict = {'_id':ctx.author.id, 'notes':[]}
            NotesUpdateDict['notes'].append(args)
            NBNotes.update(NotesUpdateDict)
            x = notesCol.insert_one(NBNotes)
            await ctx.send("Ok, Noted")
        else:
            pass
    except:
        await ctx.send("Some error occurred")

Can someone help with this? Another thing, I am using motor for asyncio, not pymongo.

EDIT: Here's the error: enter image description here

CodePudding user response:

You need to await db.NoteBoyNotes.find_one so that you get the returned value instead of the future.

Also I believe find one Returns a single document, or None if no matching document is found. so you check if check is None rather than len().

CodePudding user response:

This answer is from a comment posted by @kpie,

@client.command()
async def makenotes(ctx, *, args):
    try:
        check = await db.NoteBoyNotes.find_one({'_id':ctx.author.id})
        if (check is None):
            NotesUpdateDict = {'_id':ctx.author.id, 'notes':[]}
            NotesUpdateDict['notes'].append(args)
            NBNotes.update(NotesUpdateDict)
            x = notesCol.insert_one(NBNotes)
            await ctx.send("Ok, Noted")
        else:
            pass
    except:
        await ctx.send("Some error occurred")```

CodePudding user response:

Try this:

@client.command()
async def makenotes(ctx, *, args):
    try:
        check = awaut db.NoteBoyNotes.find_one({'_id':ctx.author.id})
        if (len(check) == 0):
            NotesUpdateDict = {'_id':ctx.author.id, 'notes':[]}
            NotesUpdateDict['notes'].append(args)
            NBNotes.update(NotesUpdateDict)
            x = notesCol.insert_one(NBNotes)
            await ctx.send("Ok, Noted")
        else:
            pass
    except:
        await ctx.send("Some error occurred")
  • Related