問題描述
InvalidDocument:無法編碼對象:<pymongo.cursor.Cursor 對象位於 (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)
‑‑‑‑‑
參考解法
方法 1:
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})))
(by zakdances、Rostyslav Dzinko)