0

So I'm trying to learn Flask and MongoDB using MongoAlchemy and I'm running into an issue when trying to query my app for data, I'm not sure what I'm doing wrong. I've searched through the MongoAlchemy documentation and followed a few StackOverflow posts to no real avail. Here's my code:

from flask import Flask, jsonify, request
from flask_mongoalchemy import MongoAlchemy

app = Flask(__name__)
app.config['MONGOALCHEMY_DATABASE'] = 'user'
app.config['MONGOALCHEMY_SERVER_AUTH'] = False
db = MongoAlchemy(app)

class User(db.Document):
    user_name = db.StringField()
    password = db.StringField()
    first_name = db.StringField()
    last_name = db.StringField()
    phone_number = db.StringField()

def init_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

user_1 = User(user_name = "user1", 
    password = "password", 
    first_name = "John", 
    last_name = "Doe",
    phone_number = "123-456-7890")

user_1.save()

@app.route('/', methods=['GET', 'POST'])
def index():
    return "Hello, world!"

@app.route('/user/<user_name>', methods=['GET', 'POST'])
def findUser(user_name=None):
    uName = request.args.get('user_name', user_name)
    user = User.query.filter({User.user_name:uName}).first()
    return jsonify(user)


##=====================================================================

if __name__ == '__main__':
    app.run(debug=True)

When I go to localhost:5000/user/user1 it returns null, I'm not sure what I'm doing wrong? Thanks in advance!

Referenced Posts: MongoAlchemy query embedded documents

Flask Value error view function did not return a response

http://www.mongoalchemy.org/api/schema/document.html

CGideon
  • 143
  • 2
  • 15
  • It isn't returning null for me, but there's an error in your code nevertheless. MongoAlchemy records are not json serializable. You need to use the `wrap` method to get the data as a dictionary, and then ignore or convert to string the `_id` key of the dictionary, as its value is not serializable either. – Luis Orduz Jun 12 '17 at 15:31
  • Thanks for the reply! I removed the jsonify call, but I'm not sure how to use wrap. Could you maybe link to documentation or an example of how to use wrap? I still can't seem to get it to return anything. – CGideon Jun 12 '17 at 16:03
  • `user = user.wrap()` would make user a python dictionary containing the raw data. Afterwards you should remove the `_id` property of that dictionary, with `user.pop('_id')`, for example. Another options is changing the value of `user['_id']` to be the raw `_id` string instead of an `ObjectID` instance, of course. – Luis Orduz Jun 12 '17 at 16:08
  • I added the below code to the /user route `@app.route('/user/', methods=['GET', 'POST']) def findUser(user_name=None): uName = str(request.args.get('user_name', user_name)) user = User.query.filter(User.user_name == uName).first() user.wrap() user.pop('_id') return user` I'm getting this error though, AttributeError: 'NoneType' object has no attribute 'wrap' am I not saving my document correctly? – CGideon Jun 12 '17 at 16:56
  • Yes, now that I notice, the first line of the function (`uName = ...`) is completely redundant. The path is already giving you the username with the `user_name` parameter. What happens if you try the query as `User.query.filter({'user_name': user_name})`? Finally, `wrap()` doesn't work in place. You need to reassign, like this: `user = user.wrap()`. However, it does seem as if the query is not returning anything, try querying mongo directly to see if the data is there. – Luis Orduz Jun 12 '17 at 17:06
  • If I do User.query.filter({'user_name': user_name}) I get a AttributeError: 'bool' object has no attribute 'obj' error. I'm guessing it's an issue with my local MongoDB instance. – CGideon Jun 12 '17 at 17:18

0 Answers0