我对猫鼬来说比较新,并试图寻找答案,但到目前为止似乎没有任何工作。
我正在查询我的mongoDB(托管在mlab上)并且只想将对象文字传递给前端模板(使用hoganjs进行模板化以及快速路由)。
当我确实传递它时,响应不是对象字面值,即使我在响应上执行JSON.parse,它仍然无效。
我需要它是一个填充了集合中项目的对象文字的数组,这样在前端,我可以遍历返回的项目。
我怎么能让它像这样工作呢?我查看了文档和一些堆栈溢出帖子,但正如我所说,没有任何工作。
这是我目前的代码:
index.js(路线):
数据库连接:
mongoose.connect("CONNECTION URL IS HERE, JUST REMOVED SINCE I AM POSTING THIS SNIPPET ONLINE");
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
var timelineItemsSchema = mongoose.Schema({
postedTime: String,
postedPlace: String,
postedContent: String,
postedTitle: String,
});
var timelineItems = mongoose.model('timelime_items', timelineItemsSchema);
timelineItem = new timelineItems({
"postedTime": "21/03/2016 13:44",
"postedPlace": "facebook",
"postedContent": "blah blah blah?",
"postedTitle": "Post Two"
});
timelineItem.save(function(err, item) {
if (err) return console.error(err);
console.log("item saved!")
});
timelineItems.find(function(err, items) {
if (err) return console.error(err);
dbResponseItems = items;
})
});
传递到前端:
res.render('index', {
page_title: "Timeline",
author: "",
nav_links: link_info,
dbResponse: dbResponseItems
});
前端需要执行以下操作:
(function() {
let $timeline = $("ul.timeline"),
jsonResponse = {{dbResponse}}; //Array of the object literals to be looped should go here
//and I should be able to loop it here, I know this loop works because I had a "dummy" array of object literals during prototyping, now I need an actual one to come back from the db filled with the object literals
for (let i = 0; i < jsonResponse.length; i++) {
let postedTime = jsonResponse[i].postedTime,
postedPlace = jsonResponse[i].postedPlace,
postedContent = jsonResponse[i].postedContent,
postedTitle = jsonResponse[i].postedTitle,
templateOne = `<li>
<div class="timeline-badge"><i class="glyphicon glyphicon-plus"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">${postedTitle}</h4>
<p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> ${postedTime} via ${postedPlace}</small></p>
</div>
<div class="timeline-body">
<p>
${postedContent}
</p>
</div>
</div>
</li>`,
templateTwo = `<li class="timeline-inverted">
<div class="timeline-badge"><i class="glyphicon glyphicon-minus"></i></div>
<div class="timeline-panel">
<div class="timeline-heading">
<h4 class="timeline-title">
${postedTitle}
</h4>
<p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> ${postedTime} via ${postedPlace}</small></p>
</div>
<div class="timeline-body">
<p>
${postedContent}
</p>
</div>
</div>
</li>`;
if (i % 2 === 0) { // index is even
$timeline.append(templateOne);
} else { //index is odd
$timeline.append(templateTwo);
}
}
})();
有什么想法吗?
如果您需要更多信息,请在评论部分询问,毫无疑问,这可能是我误解的内容,但在找到解决方案30-40分钟后我迷失了!
答案 0 :(得分:0)
我建议你在服务器端检查包含 dbResponseItems 的内容,它应该是全局变量。确保将可靠的内容传递给前端模板