我已经阅读了教程,因为我使用了三个单独的东西:1。Flask作为服务器2. PyMongo作为MongoDB驱动程序3. PyMODM作为模式创建者
我已经困惑了。
首先,我使用PyMODM定义了Schema:
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)
从上面我的想法是制作两种类型的模式:目标和路径。最后,目标看起来像这样:
{
"position": {
"x": "1",
"y": "6"
},
"orientation": {
"x": "0"
}
}
而Path将是一个目标列表。拥有我的架构,最大的问题是,我如何使用它来与我的MongoDB数据库进行通信?这是我的小型服务器代码:
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:[email protected]/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)
因此,只关注路径'/ goal'上的GET方法,如何从数据库中检索所有目标消息?
另外,我想知道如何在'/ goal /'中检索最后一个目标消息?
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find()
return jsonify(goals)
您已经在检索目标集合中的所有记录。下面的示例将为您提供单个最新记录。
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find().sort({'_id',-1}).limit(1)
return jsonify(goals)
.
def goals():
if request.method == 'GET':
goals = mongo.db.goals.find().sort({'_id',-1})
return jsonify(goals)
上面的示例将按降序返回目标集合中所有数据的列表,这意味着最后的更新将位于顶部
寻找
mongo.db.goals.find_one({"_id": ObjectId(id)})