简体   繁体   English

如何使用 mongoose 中的用户数组 object id 返回文档数组?

[英]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.我正在尝试使用用户身份验证和授权创建一个简单的后端博客 api。 It is built with mongoose and express.它是用 mongoose 和快递建造的。 In my userSchema, I have a property that is an array called "subscribedTo".在我的 userSchema 中,我有一个属性,它是一个名为“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. subscribedTo 数组存储了希望订阅的用户的 objectID。

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.当我对这条路线使用 postman 时,它返回 [] 这是可以理解的。 I can't seem to res.send(blogs) even though the blogs variable returns correctly in the forEach function.即使 blogs 变量在 forEach function 中正确返回,我似乎也无法 res.send(blogs)。

Is there a better way to do this?有一个更好的方法吗?

You can find all the documents without a foreach loop, use $in您可以在没有 foreach 循环的情况下找到所有文档,使用 $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)
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从数组创建用户并以猫鼬返回其ID? - How to create users from array and return their ids in mongoose? 使用 mongoose 从数组中返回匹配的文档 - return documents that match from an array using mongoose 如何使用对象 ID 数组创建猫鼬模式? - How To Create Mongoose Schema with Array of Object IDs? 使用 express 和 mongoose,如何使用 POST 路由将多个 ID 的数组从客户端发送到服务器端? - Using express and mongoose, how do I send an array of multiple IDs from the client-side to server-side using a POST route? 如何使用 MirageJS 中的工厂返回字符串 ID 数组? - How do you return an array of string ids using a factory in MirageJS? 如何使用 mongoose 在循环中迭代 mongoose 返回的文档数组? - How can i iterate mongoose returned documents array in loop using mongoose? 如何基于使用数组传递给Kendo Grid的Ids在MVC应用程序中返回数据? - How do I return data in my MVC application based on Ids passed in using an array to a Kendo Grid? 如何将 ID 数组作为字符串而不是 object 和 Mongoose - How to get an array of IDs as strings instead of object with Mongoose 如何在 mongoose 的数组中返回匹配的 object - How to return a matched object inside an array in mongoose 如何返回该对象数组的总数? - How do I return the total of this object array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM