RejectedSoftware Forums

Sign up

How to write a function that accepts a mongodb collection as parameter ?

Hello !

I'm trying to write a function that accepts a mongodb collection cursor as parameter but I do not know how to do that as cursor is a template type.

Can anyone give some help on this ?

protected void sendCollectionListAsDataArrayJson2(??????auto??????? collection_list, HTTPServerResponse res, in string[] fields)
{

if(!collection_list.empty)
{
	auto buf = appender!string();
	buf.put("{\"data\":[\n");
	int count = 0;
	foreach(doc; result)
	{
		if(count++ > 0)
		{
			buf.put(",");
		}
		
		buf.put("[");
		
		int count2 = 0;
		foreach( string fld; fields )
		{
			Bson v = doc[fld];
			if(count2++ > 0)
			{
				buf.put(",");
			}
			buf.put(v.toJson().toString());
		}
		
		buf.put("]\n");
	}
	buf.put("]}\n");
	res.writeBody(buf.data, "application/json");
}

}

protected void sendCollectionListAsDataArrayJson(MongoClient mongodb, HTTPServerResponse res,

const string collection_name, int limit, in string[] fields)

{

auto result = getCollectionList(mongodb, res, collection_name, limit);
sendCollectionListAsDataArrayJson2(result, res, fields);

}

Cheers !

Re: How to write a function that accepts a mongodb collection as parameter ?

On Thu, 23 Oct 2014 02:01:07 GMT, Domingo Alvarez Duarte wrote:

Hello !

I'm trying to write a function that accepts a mongodb collection cursor as parameter but I do not know how to do that as cursor is a template type.

Can anyone give some help on this ?

You can use template too:

protected void sendCollectionListAsDataArrayJson2(T)(T collection_list, HTTPServerResponse res, in string[] fields) {
...
}

Re: How to write a function that accepts a mongodb collection as parameter ?

On Thu, 23 Oct 2014 05:13:14 GMT, Jack Applegame wrote:

On Thu, 23 Oct 2014 02:01:07 GMT, Domingo Alvarez Duarte wrote:

Hello !

I'm trying to write a function that accepts a mongodb collection cursor as parameter but I do not know how to do that as cursor is a template type.

Can anyone give some help on this ?
You can use template too:

protected void sendCollectionListAsDataArrayJson2(T)(T collection_list, HTTPServerResponse res, in string[] fields) {
...
}

I'd also usually recommend to just look at a MongoCursor as a general input range to make the code more generic:

import std.range : isInputRange;

protected void sendCollectionListAsDataArrayJson2(R)(R collection_list, HTTPServerResponse res, in string[] fields)
	if (isInputRange!R)
{
	...
}

alternatively, you can also specialize the template to only accept MongoCursor to make the code more specific and to document/enforce correct usage:

import std.traits: isInstanceOf;

protected void sendCollectionListAsDataArrayJson2(R)(R collection_list, HTTPServerResponse res, in string[] fields)
	if (isInstanceOf!(MongoCursor, R))
{
	...
}