Question to tutorial and inserting data

57 views
Skip to first unread message

Thomas Klinger

unread,
May 29, 2019, 5:42:26 AM5/29/19
to MongoEngine Users
Hi,

I'm really new to MongoEngine and MongoDB, but I try to learn it at the moment. Therefore I've gone through the tutorial from the docs page and have a question on this.

In the tutorial you create an object by adding a user to the collection. In the example the objects are named "john" and "ross". Now, adding posts with this information is not the problem, but how do I insert data later on, i.e. when I try to insert data later on?

I tried to get the correct user again in a new session:

from mongoengine import *
from testdb import *

connect
('testdb')
john
=User.objects(first_name="john").first()
ross
=User.objects(first_name="ross").first()

post1
= TextPost(title="Awesome posting!", author=john)
post1
.content = "My sample text!"
post1
.tags=['awesometag']
post1
.save()

Now, the only thing I get is an error:
bson.errors.InvalidDocument: cannot encode object: [<User: User object>], of type: <class 'mongoengine.queryset.queryset.QuerySet'>

So, my question on this would be how to insert a posting to this specific user without specifying it again with "User(first_name=....)"? Imagine if there will be passwords saved in the User collection.

Many thanks in advance for your answers and maybe apologize this newbie question.

Regards, Thomas

Thomas Klinger

unread,
May 29, 2019, 6:13:51 AM5/29/19
to MongoEngine Users
I think I might have found a solution. get() seems to solve that problem:

ross=User.objects.get(first_name="Ross")
post
=LinkPost(title="Awesome video",author=ross)
post
.link_url="https://youtube.com"
post
.tags=['youtube']
post
.save()

And it does the job, the post is saved.

Regards, Thomas
Reply all
Reply to author
Forward
0 new messages