javascript - 如何使用nodejs为网站创建标签系统?

标签 javascript node.js mongodb express tagging

我正在使用 Node js 创建一个 CMS 博客,但我未能为帖子创建标记系统,我希望此标记系统连接到 MongoDB,以便我可以对每个标记执行 CRUD 操作并根据标签搜索帖子。

我为前端创建了这些代码:

//enter something in textbox and press enter....
var tags = [];
$(document).ready(function () {

    $('body').on('click', 'span.cross', function () {
        var removedItem = $(this).parent().contents(':not(span)').text();
        $(this).parent().remove();
        tags = $.grep(tags, function (value) {
            return value != removedItem;
        });
    });

    $("#textBox").keypress(function (e) {
        if (e.which === 13) {
            $(".target").append("<a href='#' class='tag' >" + this.value + '<span class="cross">X</span>' + "</a>");

            tags.push(this.value);
            this.value = "";
        }
    });
});

演示:http://jsfiddle.net/IrvinDominin/pDFnG/

我的问题从这里开始,我不知道帖子标签的性质,所以我无法为此编写任何代码,你建议我做什么?

最佳答案

最简单的解决方案是将标签元素作为数组保存到每个帖子文档中,并在其中简单存储字符串列表。 然后用户可以指定他们想要的标签,代码不需要知道它们是什么,它只是存储它们。

然后,Mongo 可以为您提供所有标签的独特列表:

db.posts.distinct('tags')

并搜索包含特定标签或标签列表的任何帖子:

db.posts.find({tags: {$in: ['tag1', tag2', 'tag3']}})

这是我在那里编写的 CLI 命令,如果您使用 Mongoose 或类似的命令,它们会略有不同。

这有帮助吗?

关于javascript - 如何使用nodejs为网站创建标签系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59398578/

相关文章:

node.js - Mongoose {严格: throw} doesn't throw error

javascript - (AngularJS) 如何遍历数组

javascript - 空后无法添加到ul

node.js - 如何在 Sequelize 中更新对象

mongodb - 查询以检索文档中涉及的所有行

mongodb - 使用 CQRS 和 dotnet 和 MongoDb 的 Kubernetes 部署策略

javascript - Google Map Javascript API 不在 Ruby 循环中显示 InfoWindows

javascript - jQuery slideToggle 在下拉动画结束时跳转

javascript - 使用 req.data 将值从中间件传递到 Restify 中的 Controller 不起作用?

node.js - .env 文件中的 key 在 NodeJS 中不起作用