【问题标题】:mongoengine: test1 is not a valid ObjectIdmongoengine:test1 不是有效的 ObjectId
【发布时间】:2014-10-15 19:15:49
【问题描述】:

我收到以下错误消息:

$ 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?

【问题讨论】:

    标签: python pymongo mongoengine


    【解决方案1】:

    根据文档: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)

    【讨论】:

    • 不幸的是,您的代码示例仍然出现同样的错误。
    【解决方案2】:

    两件事:

    ObjectId 收到一个 24 十六进制字符串,你不能用那个字符串初始化它。例如,您可以使用'53f6b9bac96be76a920e0799''111111111111111111111111' 等字符串来代替'test1'。你甚至不需要初始化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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2020-11-02
      • 1970-01-01
      • 2012-08-12
      • 2015-04-30
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多