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

Time:07-25

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

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

CodePudding user response:

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,
  },
]);
  • Related