mongoengine:test1不是有效的ObjectId

时间:2014-08-22 01:45:29

标签: python pymongo mongoengine

我收到以下错误消息:

$ python tmp2.py
why??
Traceback (most recent call last):
  File "tmp2.py", line 15, in <module>
test._id = ObjectId(i[0])
  File "/home/mictadlo/.virtualenvs/unisnp/lib/python2.7/site-packages/bson/objectid.py", line 92, in __init__
self.__validate(oid)
  File "/home/mictadlo/.virtualenvs/unisnp/lib/python2.7/site-packages/bson/objectid.py", line 199, in __validate
raise InvalidId("%s is not a valid ObjectId" % oid)
bson.errors.InvalidId: test1 is not a valid ObjectId

使用此代码:

from bson.objectid import ObjectId
from mongoengine import *


class Test(Document):
    _id = ObjectIdField(required=True)
    tag = StringField(required=True)


if __name__ == "__main__":
connect('dbtest2')
print "why??"
for i in [('test1', "a"), ('test2', "b"), ('test3', "c")]:
    test = Test()
    test._id = ObjectId(i[0])
    test.char = i[1]
    test.save()

如何使用自己独特的ID呢?

2 个答案:

答案 0 :(得分:0)

根据文档:http://docs.mongoengine.org/apireference.html#fields,ObjectIdField是'围绕MongoDB的ObjectIds的字段包装器'。因此它不能接受字符串test1作为对象ID。

您可能需要将代码更改为以下内容:

 for i in [(bson.objectid.ObjectId('test1'), "a"), (bson.objectid.ObjectId('test2'), "b"), (bson.objectid.ObjectId('test3'), "c")]:

让你的代码工作(假设test1等是有效的id)

答案 1 :(得分:0)

两件事:

ObjectId收到24个十六进制字符串,您无法使用该字符串初始化它。例如,您可以使用'test1''53f6b9bac96be76a920e0799'等字符串代替'111111111111111111111111'。您甚至不需要初始化ObjectId,您可以执行以下操作:

...
test._id = '53f6b9bac96be76a920e0799'
test.save()
...

我不知道你想用_id做什么。如果您正在尝试为您的文档生成和id字段或“主键”,则没有必要,因为会自动生成一个。你的代码是:

class Test(Document):
    tag = StringField(required=True)

for i in [("a"), ("b"), ("c")]:
    test = Test()
    test.char = i[0]
    test.save()

print(test.id)  # would print something similar to 53f6b9bac96be76a920e0799

如果您坚持使用名为_id的字段,则必须知道您的id将是相同的,因为在内部,MongoDB将其称为_id。如果您仍想使用string1作为标识符,则应执行以下操作:

class Test(Document):
    _id = StringField(primary_key=True)
    tag = StringField(required=True)