yourfriendzak yourfriendzak - 4 months ago 86
Python Question

Pymongo forEach formatting

How can I format a forEach function so that it can rest on multiple lines without causing a syntax error? Something like

function(u) {
u.forSong ={}, {'_id': 1})

lvc lvc

To pass javascript code in from Python, you need to wrap it in a bson.Code object, since otherwise Python itself (rather than PyMongo) will try to parse it. This gives you:

import bson
self.request.db.myCollection.find().forEach(bson.Code( '''
    function(u) { 
       u.forSong ={}, {'_id': 1})

But the fact that you're using self in there makes it look like you want to use Python code there, not javascript code. From the documentation, it looks like the Cursor object returned from find implements Python's Sequence protocol - meaning you ought to just be able to use a regular Python loop instead of forEach (which the docs seem to say that PyMongo doesn't implement anyway):

for u in self.request.db.myCollection.find():
   u.forSong ={}, {'_id': 1})