[英]mongodb returns Cursor, I loop through and add objects into an array, how do I send the array to the client side without third party libraries?
到目前为止,这是我所做的:
router.get('/', function(req, res, next) {
mongo.connect('mongodb://localhost:27017/interview_prac', function(err, db) {
var item = []
if (err)
throw err;
else {
var nettuts = db.collection('nettuts')
var p1 = new Promise(function(resolve, reject) {
nettuts.find({gender: 'm'}, function(err, data) {
if (err)
throw err
if (data) {
data.forEach(function(myDoc) {
item.push(myDoc)
})
}
});
});
p1.then(
res.render('index', {data: item})
).catch(function(reason) {
console.log(reason)
});
}
})
});
我想将item
发送到客户端,但是,它会在myDoc
添加到项目之前得到发送。 我正在使用Promise,页面会渲染。 但是,项目中没有任何内容。 当我用data:'hello'
替换data:item
时, hello
确实出现在客户端。
我认为您打算致电res.render('index', {data: item});
使用item
对象而不是data
对象。
Node 6+具有Promises,而MongoDB 2.2客户端返回了本地Promise,因此您不需要任何第三方库(尽管我会推荐Bluebird )
let db = null
app.get('/', function(req, res, next) {
let items = []
mongo.connect('mongodb://localhost:27017/nettuts')
.then(db => {
let nettuts = db.collection('nettuts')
return nettuts.find({gender: 'm'}).toArray()
})
.then(data => {
if (data) data.forEach(myDoc => items.push(myDoc));
console.log(data)
res.render('index', {data: items})
db.close()
})
.catch(err => next(err))
})
一些注意事项
items.push
在此是多余的,因为您已经有data
数组,但是我再次假设您正在测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.