[英]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?有一个更好的方法吗?
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.