Skip to content Skip to sidebar Skip to footer

What Structure For Create Tree Category And Set In Posts Is Better? And Find Posts By Selected Category In Mern

I'm using MERN to develop my project, I have tree category with this structure: {id: { type: Number }, parent_id: { type: Number }, name: { type: String }, sub: { t

Solution 1:

I see that you're using $all operator.

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: [ , ... ] } }

In your case, you're looking for an object "req.params.category" that has this value:

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

Try this:

// data declaringconst { category } = req.params// destructuring  const posts = await Post.find({ category: category }).sort({ date: -1 });

// It's the sameconst posts = await Post.find({ category: 
 { 
  "0": "1",
  "1": "101",
  "2": "1001"
 }
}).sort({ date: -1 })

Also, if finally posts equals to cursor , use .next() to converto to the final result.

posts.next() 

I hope it works for you. Greetings.

Solution 2:

I think this structure is not logical so I change my post body to:

{"_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}

and my schema is:

constPostSchema=newmongoose.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
}

});

but the problem it's i can`t find on my category array with this code:

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!');
}

});

this return empty array [], I don't know why!

when I get all posts in console log my result is:

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

Solution 3:

The problem was solved this way: link

But I'm still happy to share your experiences about content categorization

so my final get posts by category is:

router.get('/category/:category', async (req, res) => {
try {
    const posts = awaitPost.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!');
}

});

Post a Comment for "What Structure For Create Tree Category And Set In Posts Is Better? And Find Posts By Selected Category In Mern"