zakdances
zakdances

Reputation: 23685

InvalidDocument: Cannot encode object: <pymongo.cursor.Cursor object at

I'm trying to store one documents objectID into another as an attribute (linking) but mongo keeps giving me this error. What is wrong with this line's syntax?

for u in self.request.db.lyrics.find():
    u['forSong'] = self.request.db.song.find({}, {'_id': 1})
    self.request.db.lyrics.save(u)

Upvotes: 3

Views: 7859

Answers (1)

Rostyslav Dzinko
Rostyslav Dzinko

Reputation: 40765

The problem is that the result of find method is a cursor, not a list of objects

u['forSong'] = self.request.db.song.find({}, {'_id': 1})

is cursor, not an object. So you must convert returned cursor to list for doing your task:

u['forSong'] = list(self.request.db.song.find({}, {'_id': 1}))

That will save list of dicts like {'_id': object-id} into "forSong" field. To actually receive list of object ids you must make further conversion, e.g:

from operator import itemgetter
...
u['forSong'] = map(itemgetter('_id'),
                   list(self.request.db.song.find({}, {'_id': 1})))

Upvotes: 4

Related Questions