'Insert a document with Flask-PyMongo

I have a MongoDB database and I want to use Flask-PyMongo to work with it in my Flask app. How do I add a database and a collection so I can add user documents?

from flask import Flask, render_template, url_for
from flask.ext.pymongo import PyMongo

app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'microblogdb'
app.config['MONGO_URI'] = 'mongodb://briangunsel:password@microblog:27017/microblogdb'
mongo = PyMongo(app, config_prefix='MONGO')


@app.route('/')
def home():
    posts = mongo.db.posts.find({})
    return render_template('users.html', posts=posts)

app.run(debug=True)

Update: With only that code above, when I start up the server (python init.py) and I go to load the web page, it loads for about 10 seconds and then gives me this error https://gist.github.com/anonymous/62ca41e98e67b304838d. I am running the database microblogdb in another cmd prompt, and I set the mongo --dbpath to \data\, which is a folder I created in the microblog folder. Through the mongo interpreter, I added a posts collection, it is still giving me the same error.



Solution 1:[1]

mongo.db.users returns the users collection on the database you configured. Flask-PyMongo is using the PyMongo driver, which has extensive documentation. PyMongo's tutorial explains how to insert a document. You already have code that fetches the users who have online=True.

app.config['MONGO_URI'] = 'mongodb://username:password@host:port/db_name'
user_id = mongo.db.users.insert_one({'name': 'david'}).inserted_id

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1