Javascript 使用模板&x2B;循环mongodb.find().toArray();AJAX
在本地运行一个基本的AJAX web应用程序,其中一个表单通过Express/Node.js将数据发布到MongoDB,一个按钮onClick在div框中呈现Mongo文档时作出响应 用于模板化,单击按钮仅返回一个右大括号以显示在html div框中。console.log(返回值);正在列出mongoDB文档 } 如何对其进行编辑以循环浏览每个MongoDB文档? app.jsJavascript 使用模板&x2B;循环mongodb.find().toArray();AJAX,javascript,ajax,node.js,mongodb,express,Javascript,Ajax,Node.js,Mongodb,Express,在本地运行一个基本的AJAX web应用程序,其中一个表单通过Express/Node.js将数据发布到MongoDB,一个按钮onClick在div框中呈现Mongo文档时作出响应 用于模板化,单击按钮仅返回一个右大括号以显示在html div框中。console.log(返回值);正在列出mongoDB文档 } 如何对其进行编辑以循环浏览每个MongoDB文档? app.js function getAllDOCs(res) { db.collection('dbCollectio
function getAllDOCs(res) {
db.collection('dbCollectionName').find({}, {"_id":0}).toArray(function (err, docs) {
console.log("this did getAllDocs");
console.log("Got the DOCs: " + docs);
var returnValue = "";
for (var i = 0; i < docs.length; i++)
{
if (returnValue == "")
{
returnValue = returnValue + JSON.stringify(docs[i]);
}
else
{
returnValue = returnValue + ", " + JSON.stringify(docs[i]);
}
console.log(docs[i]);
}
console.log(returnValue);
res.render('wrapper', { allDOCs: returnValue });
});
}
index.html AJAX:
// handle FIND button clicks
$('#findButton').click(function() {
// make an ajax call
$.ajax({
dataType: 'jsonp',
jsonpCallback: '_wrapperGet',
data: $('#theForm').serialize(),
type: 'POST',
url: "http://localhost:9090",
success: handleFINDbuttonResponse,
error: handleFINDbuttonError
});
});
function handleFINDbuttonResponse(data)
{
// alert("Response! " + data);
// parse the json string
var jsonObject = JSON.parse(data);
$('#theResponse').append( jsonObject.getting );
}
index.html:
<!-- For the Returned Fields -->
<div id="theResponse">
</div><!-- /.theResponse -->
我不确定我是否理解这个问题find
toArray
向回调发送一个数组。不熟悉Swig——但我猜你会通过res.render('wrapped',{allDocs:docs})
,然后在模板中对allDocs中的d进行。。现在用数组响应,尽管数组只包含[object]。。?谢谢你的评论!已经相应地更新了问题。console.log
就是这样显示的。例如,只需尝试console.log(docs[0])
即可显示其中一个元素。
<!-- For the Returned Fields -->
<div id="theResponse">
</div><!-- /.theResponse -->