简体   繁体   中英

MongoDB - Create object with reference manually - DBRef doesn't work

for testing purposes I need to create manually some objects in a MongoDB. My Class has a reference field to another class. The referred object already exists.

I tried to put the Mongo-ID of my existing object as a value in my new object but I get the following error:

A ReferenceField only accepts DBRef: ['attribute'])

Now my question: Where do I get or find this DBRef ?


An example: I have a user in my db. I want to create a group which has the existing user as "creator" . When I put the user-ID into the creator-field I get the error...

Edit:

I just found this link MongoDB - DBRef but the solution does not work for me...

item : {"$ref" : "fruit", "$id" : "1"}

My code is like this:

{ "name" : "MyGroup", "created_at" : "2011-05-22T00:46:38", "creator": { "$ref": "user", "$id": "501bd5ac32f28a1278e54435" } }

Another edit:

Even the Mongo doc says I'm using the right format... http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON . But still not working.

In the question you referenced , the user is using a numeric string as their document ID. In your case, it looks like you're working with the more-common ObjectId but inserting it as a string. Assuming you're using PyMongo, you probably want to use the ObjectId class for the $id property of the DBRef .

If you know all such references are going to point to the same DB and collection, it may make sense to use manual references (just storing the target document's _id ) instead of DBRef objects. This is explained in more detail in the Database References documentation .

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