Pymongo find by _id field

1

I'm trying to check my Mongo database to find a value for the "_id" field with the value returned by the url_for () function from the template. Although I have verified that the value that appears in the URL and the one that passes to the router is correct, the database does not return any matches.

Here is the router code:

from flask import Flask
from flask import render_template
import pymongo
from pymongo import MongoClient
import re
from bson.objectid import ObjectId

try:
    dbClient = MongoClient().fabrica.fichas
    print("successful connection to fichas")
except:
    print('An error occurred on line {} in statement {}'.format(line, text))
    exit(1)

app=Flask(__name__)

@app.route('/ficha/<id>')
def ficha(id):
    id=ObjectId(id)
    print(id)
    return render_template('ficha.html', ficha_data=dbClient.find({"_id":ObjectId(id)}))

And this is the template code:

<!doctype html>
<title>Hello from Flask</title>
  <h2>Fichas</h2>
  <style>th{text-align: left; width: 15%;}</style>
  <table id="navigation">
        <tr>
            <th>Ref</th>
            <th>Name</th>
            <th>Leather</th>
            <th>Color</th>
            <th>Client</th>
        </tr>
    {% for ficha in datos %}
        <tr>
            <td><a href="{{ url_for('.ficha', id=ficha['_id'])}}">{{ficha['ref']}}</a></td>
            <td>{{ficha['name']}}</td>  
            <td>{{ficha['leather']}}</td> 
            <td>{{ficha['color']}}</td>
            <td><a href="{{ url_for('.fichas_cliente', cliente=ficha['client']) }}">{{ficha['client']}}</a></td>
        </tr>
    {% endfor %}
  </table>

Thank you very much!

    
asked by FranDevelopez 04.12.2018 в 16:24
source

1 answer

1

your query is this:

dbClient.find({"_id":ObjectId(id)})

the field _id is a primary identification field (automatically generated by MongoDB) and in turn it is true that it behaves like an "ObjectId", but you can also query that same field with the value when it is a string. Example _id: 3828d2u3er2038eu238du

I think the correct query should be this:

dbClient.find_one({"_id": id )})

remember that "_id" being a primary identifier can not be repeated in the collection and that is why I use find_one for the query.

    
answered by 04.12.2018 / 22:16
source