【问题标题】:unable to fetch data from mongodb from results using streams/highland.js无法使用流/highland.js 从结果中从 mongodb 获取数据
【发布时间】:2016-04-29 18:45:35
【问题描述】:
我是流的新手,我正在尝试使用 reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue) 从我的集合中获取数据。
var sg = require("reactive-superglue")
var query = sg.mongodb("mongodb://localhost:27017/qatrackerdb").collection("test1")
exports.findAll = function (err, res) {
query.find()
.map(JSON.stringify)
.done(function(data) {
console.log(data)
res.end(data)
})
}
我的卷曲请求:
curl -i -X GET http://localhost:3000/queries/
【问题讨论】:
标签:
javascript
node.js
mongodb
rest
highland.js
【解决方案1】:
您的代码 sn-p 不起作用,因为 highland.js 的 .done() 不返回结果。您应该使用 Stream.each 迭代每个元素或使用 Stream.toArray 将它们全部作为一个数组。
顺便说一句,我是反应强力胶的作者。 reactive-superglue 是我(正在进行中)对 highland 流的实际使用的尝试,建立在 highland.js 之上
干杯!
【解决方案2】:
我不太确定reactive-superglue 在这里为您做什么。看起来它只是一个让不同数据源响应的高地捷径的汇编。
你可以像这样直接使用highland来做这个:
var collection = sg.mongodb("mongodb://localhost:27017/qatrackerdb").collection("test1");
return h( collection.find({}) )
.map(h.extend({foo: "bar"})
.pipe(res);
编辑:
上面的 sn-p 仍然使用reactive-superglue,但你可以只使用 node mongo 驱动:
var url = 'mongodb://localhost:27017/qatrackerdb';
MongoClient.connect(url, function(err, db) {
h( db.collection("test1").find({}) )
.map(h.extend({foo: "bar"})
.pipe(res);
});
【解决方案3】:
我能够使用这种方法检索有效负载,不确定这是否是最好的方法,非常感谢任何其他建议或解释。
exports.findAll = function (err, res) {
query.find()
.map(JSON.stringify)
.toArray(function(x){
res.end(x + '')
})
}