I have a mongo db cusor object that get converted into a list. The list is a list of dictionaries however when I go to access the value I get this error below:
in <listcomp>
for e in app.db.entries.find_one({})
TypeError: string indices must be integers
The code is listed here:
import datetime
from flask import Flask, render_template, request
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient("mongodb+srv://username:password@MicroBlog.0oxexa.mongodb.net/test")
app.db = client.MicroBlog
@app.route("/", methods = ["GET", "POST"])
@app.route("/home", methods = ["GET", "POST"])
def home():
if request.method == "POST":
content = request.form["content"]
formattedDate =datetime.datetime.today().strftime("%Y-%m-%d")
app.db.entries.insert_one({"content": content, "date": formattedDate})
mongo_entries_with_date = [
(
e["content"],
e["date"],
datetime.datetime.strptime(e["date"], "%Y-%m-%d").strftime("%b %d")
)
for e in app.db.entries.find_one({})
]
return render_template("home.html", entries = mongo_entries_with_date), 201
return render_template("home.html"), 200
Just do e = app.db.entries.find_one({})
on the line before mongo_entries_with_date
and get rid of the square brackets. or put square brackets around app.db.entries.find_one({})
.