简体   繁体   English

使用Flask-pymongo扩展通过_id在MongoDB中搜索文档

[英]Search document in MongoDB by _id using Flask-pymongo extension

I am baffled with the following problem. 我对以下问题感到困惑。

I am using Flask, flask-pymongo extension, mongodb version v2.2.0-rc0, pdfile version 4.5 我正在使用Flask,flask-pymongo扩展,mongodb版本v2.2.0-rc0,pdfile版本4.5

This is my route: 这是我的路线:

@app.route("/check/<id>")
def check(id):
   doc=conn.db.msg.find_one({'_id':id})
   return render_template('base.html',name=doc)

the id is a valid _id from a document in the msg collection, but ALWAYS return None. id是msg集合中文档的有效_id,但总是返回None。

I have tried: 我试过了:

  • pasing the ObjectId(id) but returns errortype: ObjectId not callable 使用ObjectId(id)但返回errortype:ObjectId不可调用
  • pasing the id as str(id) returns None 将id作为str(id)返回None

Any thoughts? 有什么想法吗?

UPDATE: this how the full url looks like: 更新:这个完整的URL如何:

http://127.0.0.1:8000/check/5030b628895b800de1a9a792

UPDATE2: UPDATE2:

I found a similar question with (answer) for ruby. 我发现了类似的问题(回答)红宝石。 Not sure how I can translate it to python, what sort imports/modules do I need? 不知道我怎么能把它翻译成python,我需要什么样的导入/模块?

How can I retrieve a document by _id? 如何通过_id检索文档?

UPDATE3: I tried: 更新3:我试过:

import bson
@app.route("/check/<id>")
def check(id):
id2="'"+id+"'"
doc=conn.db.msg.find_one({'_id':bson.objectid(id2) })
return render_template('base.html',name=doc)

but I get TypeError: 'module' object is not callable (it doesnt work with id either) 但我得到TypeError:'module'对象不可调用 (它也不能用于id)

when I reached 1500 I will suggest a frustation tag :-S 当我达到1500时,我会建议一个沮丧的标签:-S

UPDATE4: UPDATE4:

Finally I got it up & running! 最后我把它拿起来跑了!

here it is my solution: 这是我的解决方案:

import bson
@app.route("/check/<id>")
def check(id):
doc=conn.db.msg.find_one({'_id':bson.ObjectId(oid=str(id))})
return render_template('base.html',name=doc)

You might also want to try using ObjectId from the bson.objectid module, like so: 您可能还想尝试使用bson.objectid模块中的ObjectId ,如下所示:

from bson.objectid import ObjectId

In that case, you won't need to provide the oid kwarg. 在这种情况下,您不需要提供oid kwarg。 You'll just do something like this: 你会做这样的事情:

db_conn.msg.find_one({'_id': ObjectId(my_oid)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM