I have read the tutorials and because I am using three seperate things: 1. Flask as a server 2. PyMongo as a MongoDB driver 3. PyMODM as a schema creator
I got confused already.
First, I have defined the Schema using PyMODM:
from pymongo import TEXT
from pymongo.operations import IndexModel
from pymodm import connect, fields, MongoModel, EmbeddedMongoModel
class GoalPosition(EmbeddedMongoModel):
x = fields.IntegerField()
y = fields.IntegerField()
class GoalOrientation(EmbeddedMongoModel):
x = fields.IntegerField()
class Goal(EmbeddedMongoModel):
position = fields.EmbeddedDocumentField(GoalPosition)
orientation = fields.EmbeddedDocumentField(GoalOrientation)
class Path(MongoModel):
path = fields.EmbeddedDocumentListField(Goal)
From the above, my idea is to make two types of schemas: Goal and Path. At the end, Goal would look like this:
{
"position": {
"x": "1",
"y": "6"
},
"orientation": {
"x": "0"
}
}
And Path will be a list of Goals. Having my schema, the big question is, how can I use that to communicate with my MongoDB database? Here is my small server code:
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from flask_pymongo import PyMongo
from flask import jsonify
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb+srv://user:pass@cluster0-qhfvu.mongodb.net/test?retryWrites=true"
mongo = PyMongo(app)
@app.route('/goal', methods=['GET', 'POST'])
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find()
return jsonify(goals)
elif request.method == 'POST':
position = request.body.position
orientation = request.body.orientation
print position
flash("Goal added")
@app.route('/goal/<id>')
def goal(id):
goal = mongo.db.goals.find_one_or_404({"_id" : id})
return jsonify(goal)
So by focusing only on GET method at route '/goal', how can I retrieve all the Goal messages from my database?
Also, I want to know how can I retrieve a last Goal message at '/goal/' ?