创建树类别和在帖子中设置什么结构更好?并在 MERN 中按选定类别查找帖子

What structure for create tree category and set in posts is better? and find posts by selected category in MERN

我正在使用 MERN 开发我的项目,我的树类别具有以下结构:

{id: {
    type: Number
},
parent_id: {
    type: Number
},
name: {
    type: String
},
sub: {
    type: Boolean
}}

例如:

 {
    "_id": "5dfa22dbb04cee3960868fd8",
    "id": 1,
    "name": "Code",
    "parent_id": 0,
    "sub": true,
    "__v": 0
},
{
    "_id": "5dfa2358b04cee3960868fda",
    "id": 101,
    "parent_id": 1,
    "name": "JavaScript",
    "sub": true,
    "__v": 0
},
{
    "_id": "5dfa68735dc1004134b259ab",
    "id": 1001,
    "parent_id": 101,
    "name": "React",
    "sub": false,
    "__v": 0
},

并且对于每个 post 我有这样的结构:

    {
    "_id": "5dfd3b918937d40b98afd3f8",
    "user": "5deea38cfc84f42590e01942",
    "title": "test",
    "description": "description test",
    "category":
        {
            "0": "1",
            "1": "101"
        },
    "phone": "+1",
    "country": "USA",
    "city": "NY",
    "options": {
        "transaction_type": ""
    },
    "date": "2019-12-20T21:22:25.940Z",
    "__v": 0
}

例如,我们有 id 1 的类别 parent 和 id 101 的类别 child of 1 而 101 的 child 是 1001 就像一棵树

现在我有一个 post 类别是 1001,所以我为此 post 设置了类别,如下所示:

        "category": [
        {
            "0": "1",
            "1": "101",
            "2": "1001"
        }
    ]

和其他 post 类别是 101,所以我这样设置:

            "category": [
        {
            "0": "1",
            "1": "101",
        }
    ]

我想要当用户 select 菜单中的 ID 为 1 的类别时,return 所有 post 都有类别 1、101 和 1001,所以我使用像顶部代码这样的结构来设置 parent id 和 child id 用于 post 类别

这个方法是否正确,或者您有更好的方法建议吗?

在后端使用 express 我使用底部代码在每个类别中查找 posts 但没有工作我应该做什么?

router.get('/category/:category', async (req, res) => {
try {
    const posts = await Post.find({'category': {$all: req.params.category}}).sort({ date: -1 });
    if (!posts) {
        return res.status(404).json({ msg: 'Ads not found' });
    }
        const resultPosts = posts.slice(req.query.start, req.query.count)
        res.json(resultPosts);


} catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
        return res.status(404).json({ msg: 'Ads not found' });
    }
    res.status(500).send('Server Error!');
}});

我看到您正在使用 $all 运算符。

The $all operator selects the documents where the value of a field is an array that contains all the specified elements. To specify an $all expression, use the following prototype: { : { $all: [ , ... ] } }

在您的例子中,您正在寻找具有以下值的对象 "req.params.category":

{
 "0": "1",
 "1": "101",
 "2": "1001"
}

试试这个:

// data declaring
const { category } = req.params // destructuring  

const posts = await Post.find({ category: category }).sort({ date: -1 });

// It's the same

const posts = await Post.find({ category: 
 { 
  "0": "1",
  "1": "101",
  "2": "1001"
 }
}).sort({ date: -1 })

此外,如果最终发布等于 cursor ,请使用 .next() 转换为最终结果。

posts.next() 

希望对你有用。你好。

我认为这个结构不合逻辑,所以我将 post 正文更改为:

{
    "_id": "5ea00ded0e94961c0445bd5f",
    "category": [
        {
            "cat_id": 2,
            "cat_name": "2"
        },
        {
            "cat_id": 102,
            "cat_name": "102"
        }
    ],
    "user": "5deeaeeb06f015576080a435",
    "title": "test5",
    "description": "description5",
    "date": "2020-04-22T09:27:09.692Z",
    "__v": 0
}

我的模式是:

const PostSchema = new mongoose.Schema({
user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
},
title: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
},
category: [
    {
        cat_id: Number,
        cat_name: String
    }
],
options: {},
phone: {
    type: String,
},
country: {
    type: String,
},
city: {
    type: String,
},
date: {
    type: Date,
    default: Date.now
}

});

但问题是我无法使用以下代码在我的类别数组中找到它:

router.get('/category/:category', async (req, res) => {
try {
    const posts = await Post.find({category: {cat_name: req.params.category}})
    if (!posts) {
        return res.status(404).json({ msg: 'Ads not found' });
    }
    console.log(posts)

    res.json(posts);

} catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
        return res.status(404).json({ msg: 'Ads not found' });
    }
    res.status(500).send('Server Error!');
}

});

这个return空数组[],不知道为什么!

当我在控制台日志中获得所有 post 时,我的结果是:

{ category: [ [Object], [Object] ], _id: 5ea00ded0e94961c0445bd5f, user: 5deeaeeb06f015576080a435, title: 'test5', description: 'description5', date: 2020-04-22T09:27:09.692Z, __v: 0 }

问题是这样解决的:link

但我仍然很乐意分享您在内容分类方面的经验

所以我最终按类别获取的帖子是:

router.get('/category/:category', async (req, res) => {
try {
    const posts = await Post.find({category: {$elemMatch: {cat_name: 'req.params.category'}}})
    if (!posts) {
        return res.status(404).json({ msg: 'Ads not found' });
    }
    console.log(posts)
    res.json(posts);

} catch (err) {
    console.error(err.message);
    if (err.kind === 'ObjectId') {
        return res.status(404).json({ msg: 'Ads not found' });
    }
    res.status(500).send('Server Error!');
}

});