简体   繁体   中英

Python & MongoDb: Query not working at execution time

I have a token saved in mongo db like .

db.user.findOne({'token':'7fd74c28-8ba1-11e2-9073-e840f23c81a0'}['uuid'])
{
    "_id" : ObjectId("5140114fae4cb51773d8c4f8"),
    "username" : "jjj51@gmail.com",
    "name" : "vivek",
    "mobile" : "12345",
    "is_active" : false,
    "token" : BinData(3,"hLL6kIugEeKif+hA8jyBoA==")
}

The above query works fine when i execute in the mongo db command line interface .

The same query when i am trying to run in Django view lik.

get_user = db.user.findOne({'token':token}['uuid'])
or `get_user = db.user.findOne({'token':'7fd74c28-8ba1-11e2-9073-e840f23c81a0'}['uuid'])`

I am getting an error

KeyError at /activateaccount/
'uuid'

Please help me out why I am getting this error .

My database

 db.user.find()
{ "_id" : ObjectId("5140114fae4cb51773d8c4f8"), "username" : "ghgh@gmail.com", "name" : "Rohit", "mobile" : "12345", "is_active" : false, "token" : BinData(3,"hLL6kIugEeKif+hA8jyBoA==") }
{ "_id" : ObjectId("51401194ae4cb51773d8c4f9"), "username" : "ghg@gmail.com", "name" : "rohit", "mobile" : "12345", "is_active" : false, "token" : BinData(3,"rgBIMIugEeKQBuhA8jyBoA==") }
{ "_id" : ObjectId("514012fcae4cb51874ca3e6f"), "username" : "ghgh@gmail.com", "name" : "rahul", "mobile" : "8528256", "is_active" : false, "token" : BinData(3,"f9dMKIuhEeKQc+hA8jyBoA==") }

TL;DR your query is faulty.

Longer explanation:

{'token':'7fd74c28-8ba1-11e2-9073-e840f23c81a0'}['uuid']

translates to undefined , because you're trying to get the property uuid from an object that doesn't have that property. In the Mongo shell, which uses Javascript, that translates to the following query:

db.user.findOne(undefined)

You'll get some random (okay, not so random, probably the first) result.

Python is a bit more strict when you're trying to get an unknown key from a dictionary:

{'token':token}['uuid']

Since uuid isn't a valid key in the dictionary {'token':token} , you'll get a KeyError when you try to access it.

EDIT: since you've used Python UUID types to store the tokens in the database, you also need to use the same type in your query:

from uuid import UUID

token = '7fd74c28-8ba1-11e2-9073-e840f23c81a0'
get_user = db.user.find_one({'token' : UUID(token) })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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