【发布时间】:2018-05-23 18:43:44
【问题描述】:
我正在尝试为博客制作过滤器功能。我正在使用节点 express/MongoDB/Mongoose 设置,我想要的是单击过滤器以添加“活动”类,并将该过滤器添加到数组 (filterArray) 中。然后,我想将 filterArray 与 Mongoose 的帖子进行比较,并将匹配结果输出到 displayArray,然后循环并输出到页面。
所以我有两组不同的 javascript 数据——我的 Mongoose 对象(存储在我的 MongoDB 数据库中)以及我的脚本文件中的数组和函数。我正在努力研究如何使两者相互配合。
我的问题是:
如果我的数据是从 app.js 传递过来的,我该如何引用 app.js 中的 DOM?
或
如果我必须使用脚本来操作 dom,我如何在那里引用我的 mongoose 数据?
这是我目前所拥有的:
在我的 app.js 中:
app.get('/', function(req, res){
Post.find({}, function(err, posts){
if (err) {
console.log("There was an error: " + err);
} else {
res.render('index', {posts: posts});
}
});
});
在一个单独的脚本文件中(我在我的 ejs 视图中链接到该文件):
var filterList = ['first item'];
var month = document.getElementsByClassName("post-list__month");
function toggleFilter(element){
if (element.classList.contains('active')) {
console.log('active is there so removing it!');
element.classList.toggle('active');
filterList = filterList.filter(function(e) {
return e !== element.attributes.name.value;
console.log('Value was removed');
});
console.log(filterList);
} else {
console.log('active not there so adding it!');
element.classList.toggle('active');
filterList.push(element.attributes.name.value);
console.log(`${element.attributes.name.value} was added to filter list.`);
console.log(filterList);
}
}
然后在我看来 index.ejs(我还没有尝试执行过滤...):
<section class="middle-section">
<% if(posts.length > 0){ %>
<% for (var i = posts.length - 1; i > -1; i--) { %>
<a class="post-link" href="/posts/<%= posts[i]._id %>">
<div class="post-body">
<div class="post">
<div class="post__heading">
<h2 class="heading-secondary"><%= posts[i].title %></h2>
</div>
<div class="post__content">
<p><%= posts[i].body.slice(0, 300) %>...</p>
</div>
<div class="tags">
<span class="heading-secondary-date">
Tags: <%= posts[i].categories[0] %>, <%= posts[i].categories[1] %>
</span>
</div>
<div class="date">
<span class="heading-secondary-date">
<%= posts[i].date %>
</span>
</div>
</div>
</div>
</a>
<% } %>
<% } else { %>
<h1>BLOG LIST IS EMPTY<h1>
<% } %>
</section>
最后,这是我的 Mongoose Post 架构 - 我将比较类别与 filterList 中的类别:
var postSchema = new mongoose.Schema({
title: String,
body: String,
date: String,
categories: [],
month: String,
author: String,
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
提前感谢任何可以提供帮助的人:)
【问题讨论】:
标签: javascript node.js mongodb express mongoose