Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have an error about mongoose Error: Arguments must be aggregate pipeline operators

Hi I’m new to the mongoose I got an error that Error: Arguments must be aggregate pipeline operators this

I just try to get posts from users who I’m following

I have no idea to solve this problem. It’s my first time using aggregate function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

here’s my code

export const getPosts = async (req, res) => {
  const user = req.user;
  console.log(user);
  try {
    if (user.following.length === 0) return res.json("No following users");
    //user.following = string[]
    const followingPosts = await Post.aggregate([
      {
        $match: {
          userId: { $in: user.following },
        },
        $sort: {
          createdAt: 1,
        },
        $limit: 10,
      },
    ]);

    res.status(200).json(followingPosts);
  } catch (error) {
    console.log(error);
    res.status(404).json({ message: error.message });
  }
};

is there a good way to solve this problem let me know
I’d really appreciate it. thanks for reading my qeustion

>Solution :

Your query is syntactically wrong, you are creating one single object for different stages, and mongo expects each stage to be a separate object.

const followingPosts = await Post.aggregate([
  {
    $match: {
      userId: { $in: user.following },
    },
    $sort: {
      createdAt: 1,
    },
    $limit: 10,
  },
]);

The above syntax is wrong. Try this:

const followingPosts = await Post.aggregate([
  {
    $match: {
      userId: { $in: user.following },
    }
  },
  {  
    $sort: {
      createdAt: 1,
    },
  },
  {
    $limit: 10,
  },
]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading