RejectedSoftware Forums

Sign up

MongoCursor and templates

Hello,

I was trying to list items in a MongoCursor in a template but the foreach do not works. If I print the cursor I can see two items and the same foreach works in the d app.

app.d

auto users = conn.getCollection("db.users").find();
res.render!("index.dt", users);

index.dt

p Users already known (#{users}):
- foreach (user; users)
	p= user.name.get!string()

which print

Users already known ([{"_id":"530d014d4d9444875e000000","name":"Cif"}, {"_id":"530d01b24d9444875e000001","name":"Ciof"}]):

What am I doing wrong?
Thanks for help

Andrea

Re: MongoCursor and templates

Am 25.02.2014 23:05, schrieb Andrea Agosti:

Hello,

I was trying to list items in a MongoCursor in a template but the foreach do not works. If I print the cursor I can see two items and the same foreach works in the d app.

app.d

auto users = conn.getCollection("db.users").find();
res.render!("index.dt", users);

index.dt

p Users already known (#{users}):
- foreach (user; users)
	p= user.name.get!string()

which print

Users already known ([{"_id":"530d014d4d9444875e000000","name":"Cif"}, {"_id":"530d01b24d9444875e000001","name":"Ciof"}]):

What am I doing wrong?
Thanks for help

Andrea

The problem is that a MongoCursor can only be iterated once, because
it's live fetched from the database during the iteration. So you'd
either have to drop the (#{users}) part, or you could store the result
of std.array.array(users), which will read all users in an array, and
then use that for repeated iteration.

Re: MongoCursor and templates

On Tue, 25 Feb 2014 23:54:58 +0100, Sönke Ludwig wrote:

Am 25.02.2014 23:05, schrieb Andrea Agosti:

Hello,

I was trying to list items in a MongoCursor in a template but the foreach do not works. If I print the cursor I can see two items and the same foreach works in the d app.

app.d

auto users = conn.getCollection("db.users").find();
res.render!("index.dt", users);

index.dt

p Users already known (#{users}):
- foreach (user; users)
	p= user.name.get!string()

which print

Users already known ([{"_id":"530d014d4d9444875e000000","name":"Cif"}, {"_id":"530d01b24d9444875e000001","name":"Ciof"}]):

What am I doing wrong?
Thanks for help

Andrea

The problem is that a MongoCursor can only be iterated once, because
it's live fetched from the database during the iteration. So you'd
either have to drop the (#{users}) part, or you could store the result
of std.array.array(users), which will read all users in an array, and
then use that for repeated iteration.

Yes, right. Probably I was doing something wrong before so I putted that as debug but it didn't help :D
Thanks for the hint