返回包含来自 MongoDB 的数据的 JSON
我正在从 MongoDB 获取数据,如下所示:
@bs = coll2.find("date" => {"$gte" => initial_date, "$lte" => Time.now.utc})
它工作正常,但当我渲染 @bs 时,它发送空。
render :json => @bs
如果我执行 @bs.each 并将每个渲染为 json,它会起作用,但是,我想发送整个 @bs。
谢谢
I am fetching data from MongoDB as follows:
@bs = coll2.find("date" => {"$gte" => initial_date, "$lte" => Time.now.utc})
It works fine but when I render @bs, it sends empty.
render :json => @bs
If I do a @bs.each and render each one as json, it works, however, I want to send the whole @bs.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,#find 返回一个 Mongo::Cursor 对象,而不是实际结果。您需要首先将 cursur (
@bs
) 转换为包含结果的数组,然后将其呈现为 json。请注意,由于它是一个游标,一旦您返回结果或开始迭代它们,
to_a
调用将不会返回所有结果。您需要调用rewind!
来重置结果集:By default,
#find
returns a Mongo::Cursor object, not the actual results. You'll want to first convert the cursur (@bs
) to an array with the results in it, and then render that as json.Note that since it's a cursor, once you either return the results, or start iterating over them, then the
to_a
call will not return all the results. You'll need to callrewind!
to reset the result set: