Javascript 循环浏览MongoDB文档?
在本地运行基本AJAX web应用程序的情况下,表单通过Express/Node.js将数据发布到MongoDB,按钮onClick在div框中呈现Mongo文档时做出响应 使用模板时,单击按钮只会返回一个右大括号以显示在html div框中。 } 如何对其进行编辑以循环浏览每个MongoDB文档? wrapper.html:Javascript 循环浏览MongoDB文档?,javascript,ajax,node.js,mongodb,express,Javascript,Ajax,Node.js,Mongodb,Express,在本地运行基本AJAX web应用程序的情况下,表单通过Express/Node.js将数据发布到MongoDB,按钮onClick在div框中呈现Mongo文档时做出响应 使用模板时,单击按钮只会返回一个右大括号以显示在html div框中。 } 如何对其进行编辑以循环浏览每个MongoDB文档? wrapper.html: {% for go in allDOCs %} _wrapperGet('{"getting":"{{ keyName }}"}') {% endfor %} …其中a
{% for go in allDOCs %}
_wrapperGet('{"getting":"{{ keyName }}"}')
{% endfor %}
…其中ajax在index.html中发布包装器数据:
<!-- For the Returned Fields -->
<div id="theResponse">
</div><!-- /.theResponse -->
…来自app.js
function getAllDOCs(res) {
db.collection('dbCollectionName').find({}, {"_id":0}).toArray(function (err, docs) {
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 });
});
}
这个问题很长,涉及很多不同的话题。试着孤立你的问题,问一个简洁的问题,不要涉及太多的话题。那么回答你的问题就更容易了。为什么你要在将文档传递到模板之前手动对文档进行字符串化?@user152468将代码缩减到最相关的部分,并将帖子重新组织为更直接。。更好吗?我只是在问如何使用AJAX正确格式化模板_wrapperGet@JohnnyHK谢谢你指出这一点。。那是从我在returnValue中包含_wrapperGet时开始的。。现在不用它就试试这个!您是否尝试过创建一个数组:
returnValue=[]代码>然后推送每个文档<代码>returnValue.push(docs[i].toJSON())代码>?
function getAllDOCs(res) {
db.collection('dbCollectionName').find({}, {"_id":0}).toArray(function (err, docs) {
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 });
});
}
function handleFINDbuttonResponse(data)
{
// parse the json string
var jsonObject = JSON.parse(data);
$('#theResponse').append( jsonObject.getting );
}