1

I'm writing a blog engine using express, and ran into a problem when trying to run a mongoose query through a function:

What I'm trying to do is to obtain a variable that contains the next and previous blog posts by id, to do that I wrote this function:

middleware.getAdjacentPosts = async function(_id) {
var adjacentPosts = {}
await Post.findOne({ _id: { $gt: _id } }).sort({ _id: 1 }).exec(async function(err, nextPost) {
    if (err) {
        console.log(err)
    } else {
        if (nextPost == null) {
            adjacentPosts.nextPost = false;
        } else {
            adjacentPosts.nextPostUrl = nextPost.slug;
            adjacentPosts.nextPostTitle = nextPost.title;
        }
        await Post.findOne({ _id: { $lt: _id } }).sort({ _id: -1 }).exec(
            async function(err, previousPost) {
                if (err) {
                    console.log(err.message);
                } else {
                    if (previousPost == null) {
                        adjacentPosts.previousPost = false;
                    } else {
                        adjacentPosts.previousPostUrl = previousPost.slug;
                        adjacentPosts.previousPostTitle = previousPost.title;
                    }
                    console.log(adjacentPosts)
                    return adjacentPosts
                }

            })

    }
})

}

Before returning, I can see the variable completed with what I need through the console.log. The problem I have is that when I try to execute the function, the receiving variable is empty. This would be executed in the get route for a post, like the following:

Router.get("/posts/:slug", async function(req, res) {

await Post.findOne({ slug: req.params.slug }).populate('categories').populate('comments').exec(async function(err, foundBlog) {
    if (err) {
        console.log(err.message)
    } else {
        var posts = {}
        posts = await middleware.getAdjacentPosts(foundBlog._id)
        console.log(posts)
        res.render("frontoffice/post", {
            blog: foundBlog,
            postUrl: req.params.slug,
            adj: posts,
            reCaptchaSiteKey: process.env.CAPTCHA_SITE_KEY
        })
    }
})

})

Any clues of what I might be doing wrong?

sebasimone
  • 25
  • 4

1 Answers1

1

As @LucaKiebel suggests, you will need to return the results from your findOnes:

middleware.getAdjacentPosts = async function(_id) {
  var adjacentPosts = {};
  return await Post.findOne({ _id: { $gt: _id } })
    .sort({ _id: 1 })
    .exec(async function(err, nextPost) {
      if (err) {
        console.log(err);
      } else {
        if (nextPost == null) {
          adjacentPosts.nextPost = false;
        } else {
          adjacentPosts.nextPostUrl = nextPost.slug;
          adjacentPosts.nextPostTitle = nextPost.title;
        }
        return await Post.findOne({ _id: { $lt: _id } })
          .sort({ _id: -1 })
          .exec(async function(err, previousPost) {
            if (err) {
              console.log(err.message);
            } else {
              if (previousPost == null) {
                adjacentPosts.previousPost = false;
              } else {
                adjacentPosts.previousPostUrl = previousPost.slug;
                adjacentPosts.previousPostTitle = previousPost.title;
              }
              console.log(adjacentPosts);
              return adjacentPosts;
            }
          });
      }
    });
};

A potential improvement, since you are using async/await anyway, might be to get rid of the callbacks:

middleware.getAdjacentPosts = async function(_id) {
  var adjacentPosts = {};
  try {
    const nextPost = await Post.findOne({ _id: { $gt: _id } }).sort({ _id: 1 });
    if (nextPost == null) {
      adjacentPosts.nextPost = false;
    } else {
      adjacentPosts.nextPostUrl = nextPost.slug;
      adjacentPosts.nextPostTitle = nextPost.title;
    }
    const previousPost =  await Post.findOne({ _id: { $lt: _id } }).sort({ _id: -1 })
    if (previousPost == null) {
      adjacentPosts.previousPost = false;
    } else {
      adjacentPosts.previousPostUrl = previousPost.slug;
      adjacentPosts.previousPostTitle = previousPost.title;
    }
    console.log(adjacentPosts);
    return adjacentPosts;
  } catch (err) {
    console.log(err);
  }
};
``
abondoa
  • 1,613
  • 13
  • 23