srihari
srihari

Reputation: 1

cowboy for REST based services using mongoDB. Getting the error BSON value to JSON conversion

I am using cowboy for REST based services using mongoDB. Getting the error BSON value to JSON conversion (i.e '_id' in mongodb value) can any one is having idea, how to fetch the mongoDB documents and convert to JSON and push to Rest services

{ok, Connection} = mongo_config:connect(),
    Collection = <<"user">>,
    Selection = {},
    Userdata = mc_worker_api:find(Connection, Collection, Selection),
    Result = mc_cursor:rest(Userdata),
    mc_cursor:close(Userdata),
    io:format(" users data ~p ~n", [Result]),
    Re = jsx:encode(Result),
    Req = cowboy_req:reply(200, #{
        <<"content-type">> => <<"text/plain">>
    }, Re, Req0),
    {ok, Req, State};

Error -

Error: Ranch listener my_http_listener, connection process <0.192.0>, stream 1 had its request process <0.193.0> exit with reason badarg and stacktrace [{jsx_parser,value,4,[{file,"src/jsx_parser.erl"},{line,152}]},{user_handler,init,2,[{file,"src/user_handler.erl"},{line,19}]},{cowboy_handler,execute,2,[{file,"src/cowboy_handler.erl"},{line,39}]},{cowboy_stream_h,execute,3,[{file,"src/cowboy_stream_h.erl"},{line,172}]},{cowboy_stream_h,proc_lib_hack,3,[{file,"src/cowboy_stream_h.erl"},{line,157}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]

Upvotes: 0

Views: 144

Answers (1)

Ryan Stewart
Ryan Stewart

Reputation: 128849

The mongo client returns bson documents, which look something like {key1, value1, key2, value2, key3, value3}. To produce JSON, jsx:encode() requires input in the form of a proplist like [{key1, value1}, {key2, value2}, {key3, value3}] or a map like #{key1 => value1, key2 => value2, key3 => value3}. In other words, you can't take the output of the mongo client and pass it directly to jsx. You'll have to do some light data conversion first. Something like

to_map([]) ->
  #{}; 
to_map([K, V | Rest]) -> 
  M = to_map(Rest), 
  M#{K => V}.

Then you can:

> Bson = {key1, value1, key2, value2, key3, value3}.
> to_map(tuple_to_list(Bson)).
#{key1 => value1,key2 => value2,key3 => value3}

Upvotes: 1

Related Questions