0

I am trying to create a simple back end blog api with user authentication and authorization. It is built with mongoose and express. In my userSchema, I have a property that is an array called "subscribedTo". Here, users can subscribe to different users to get their blogs. The subscribedTo array stores objectIDs of the users that wished to be subscribed too.

Here is my code:

router.get('/blogs', auth, async (req, res) => {
//auth middleware attaches user to the request obj
    try {
    let blogs = []

    req.user.subscribedTo.forEach(async (id) => {
        let ownersBlogs = await Blog.find({owner:id})
        blogs = [...blogs, ...ownersBlogs]
        console.log(blogs)//consoles desired output of users blogs
    })
    console.log(blogs)//runs first and returns []
    res.send(blogs)

    }catch(e){
    res.status(500).send(e)
    }
})

When I use postman for this route it returns [] which is understandable. I can't seem to res.send(blogs) even though the blogs variable returns correctly in the forEach function.

Is there a better way to do this?

2 Answers 2

1

You can use without loop like as bellow

Blog.find({ owner: { $in: req.user.subscribedTo } }, function (err, blogResult) {
  if (err) {
    response.send(err);
  } else {
    response.send(blogResult);
  }
});

OR

send response after loop completed like as bellow

router.get('/blogs', auth, async (req, res) => {
  //auth middleware attaches user to the request obj
  try {
    let blogs = []
    let len = req.user.subscribedTo.length;
    let i = 0;
    if (len > 0) {
      req.user.subscribedTo.forEach(async (id) => {
        let ownersBlogs = await Blog.find({ owner: id })
        blogs = [...blogs, ...ownersBlogs]
        console.log(blogs)//consoles desired output of users blogs

        i++;
        if (i === len) {
          //send response when loop reached at the end
          res.send(blogs)
        }

      })
    } else {
      res.send(blogs);
    }

  } catch (e) {
    res.status(500).send(e)
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can find all the documents without a foreach loop, use $in

Blog.find({owner:{$in:[array of ids]}});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.