javascript - Mongoose 响应无法正确解析

标签 javascript json node.js mongodb hogan.js

我对 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);
    }
  }
})();

有什么想法吗?

如果您需要更多信息,请在评论部分询问,毫无疑问,这可能是我误解的,但在尝试找到解决方案 30 - 40 分钟后我迷失了!

最佳答案

我建议您在服务器端检查包含dbResponseItems的内容,它应该是全局变量。确保您将可靠的内容传递给前端模板

关于javascript - Mongoose 响应无法正确解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091845/

相关文章:

javascript - Socket.io 和 Async 不返回值

java - 使用 Jackson 进行 JSON 反序列化

java - 如何将 Jackson 的 ContextualDeserializer 用于根值?

带有线程暂停/恢复的 JavaScript 对话框

javascript - 如何更新在 javascript 中使用模板文字的对象值?

javascript - 在 JavaScript 中将字节解释为打包的二进制数据

ios - Swift JSON 进入TableViewCell

javascript - Vue JS 应用程序上的 Passport JS 身份验证

node.js - 从字符串转换日期和/或时间时,插入或更新日期字段会出现以下错误转换失败

Javascript (Node.js) 将 json 解构为现有变量