简体   繁体   中英

How do I return an array of documents using an array of users object ids in mongoose?

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM