Ron
Ron

Reputation: 23486

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.

Upvotes: 4

Views: 10187

Answers (1)

jmikola
jmikola

Reputation: 6922

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.

Upvotes: 5

Related Questions