【发布时间】:2016-05-07 17:51:49
【问题描述】:
我对 mongoose 比较陌生,并尝试四处寻找答案,但到目前为止似乎没有任何效果。
我正在查询我的 mongoDB(托管在 mlab 上)并且只想将对象文字传递给前端模板(使用 hoganjs 进行模板和 express 进行路由)。
当我传递它时,响应不是对象文字,即使我对响应执行 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);
}
}
})();
有什么想法吗?
如果您需要更多信息,请在 cmets 部分询问,毫无疑问,这可能是我误解了,但在尝试找到解决方案 30 - 40 分钟后我迷路了!
【问题讨论】:
-
另外,未解析的、奇怪的响应中返回的项目都是 URI 编码的,你怎么能阻止呢?
标签: javascript json node.js mongodb hogan.js