Home > Software design >  Find document from mongoose collections with specific condition
Find document from mongoose collections with specific condition

Time:08-04

Recently I start using MongoDB with Mongoose on Nodejs.

This code works as it should, and returns me all data i need :

const getAllPosts = async () => {
  try {
    return (await PostModel.find().populate('user')).reverse();
  } catch (error) {
    console.log(error);
    throw Error('Error while getting all posts');
  }
};

But now I only need individual posts, which in the tags (represented as an array in the PostModel) contain the data that I will pass in the request. For example, I will make a GET request to /posts/tag111 and should get all posts that have "tag111" in the tags array.

Any ways to do this?

CodePudding user response:

If you are using expressjs, your route should be something like:

whatever.get('/:tag', postController.getAllPostTagged)

The function you use in your route (called getAllPostTagged above) should be similar to this one, in which you get the path param tag from req:

const postController = {

    getAllPostTagged = async(req, res) => {
        try {
            return (await PostModel.find({tags: req.params.tag}));
        } catch (error) {
            console.log(error);
            throw Error('Error while getting all posts');
        }
    }
}

The key here is to know where the params are obtained (from req.params) .

  • Related