Home > front end >  How to check if no documents exist in a MongoDB collection?
How to check if no documents exist in a MongoDB collection?

Time:01-16

So, basically i have a task managing application i am working on, and i need a way to detect if there's no tasks in the database so i can make a simple jinja2 format on it.

Here is my code:

@app.route("/dashboard")
def dashboard():
    if "name" in session:
        username = session['name']
        ifTask = taskAdd.find({"name": username})
        name = session['name']
        tasknames = []
        if ifTask is None:
            return render_template('dashboard.html', noTasksDB=True)
        for x in ifTask:
            tasknames.append((x['taskname'], x['Priority'], x['Notfication']))
        return render_template('dashboard.html', dashboardPage=True, title=name "'s Dashboard", name=True, username=username, ifTask=ifTask, tasknames=tasknames, noTasksDB=False)

I tried to add the following code:

 if ifTask is None:
            return render_template('dashboard.html', noTasksDB=True)

I expected None to work, but it didn't instead the HTML remained the same .

I also tried printing ifTask when there are no current tasks in the database and all i get is some pymongo cursor which i have no idea on what it means.

Does anyone know how to fix this problem?

CodePudding user response:

If you do as the other commenter suggested, but change your comparison a bit then this should work. ifTask will be an empty list if nothing is found - and then we just check if it's empty rather than comparing it to None.

ifTask = list(taskAdd.find({"name": username}))

if not ifTask:
    return render_template('dashboard.html', noTasksDB=True)

or if you don't want to do that. Then

ifTask = taskAdd.find({"name": username})
name = session['name']
tasknames = []

for x in ifTask:
    tasknames.append((x['taskname'], x['Priority'], x['Notfication']))

if not tasknames:
    # tasknames is an empty list - no tasks
    return render_template('dashboard.html', noTasksDB=True)

return render_template(
    'dashboard.html',
    dashboardPage=True,
    title=name "'s Dashboard",
    name=True,
    username=username,
    ifTask=ifTask,
    tasknames=tasknames,
    noTasksDB=False
)

tasknames will be empty if taskAdd.find didn't find any results.

  • Related