如何将 Express.js 变量传递给 MongoDB 函数?

How can I pass Express.js variables to MongoDB functions?

我正在研究 blogging application (click the link to see the GitHub repo) with Express, EJS 和 MongoDB。

我为 post 制作了一个简单的寻呼机。

在 posts controller 我有:

exports.getPosts = async (req, res, next) => {

  const posts = await Post.find({}, (err, posts) => {

      const perPage = 10;

      const currPage = req.query.page ? parseInt(req.query.page) : 1;

      const postsCount = posts.length;

      const pageCount = Math.ceil(postsCount / perPage);

      const pageDecrement = currPage > 1 ? 1 : 0;

      const pageIncrement = currPage < pageCount ? 1 : 0;

      if (err) {
        console.log("Error: ", err);
      } else {
        res.render("default/index", {
          moment: moment,
          layout: "default/layout",
          website_name: "MEAN Blog",
          page_heading: "XPress News",
          page_subheading: "A MEAN Stack Blogging Application",
          currPage: currPage,
          pageDecrement: pageDecrement,
          pageIncrement: pageIncrement,
          posts: posts,
        });
      }
    })
      .sort({ created_at: -1 })
      .populate("category")
      .limit(perPage)
      .skip((currPage - 1) * perPage);
};

视图中的寻呼机:

<% if (posts) {%>
  <div class="clearfix d-flex justify-content-center">
    <div class="px-1">
        <a class="btn btn-primary <%= pageDecrement == 0 ? 'disabled' : '' %>" href="/?page=<%= currPage - pageDecrement %>">&larr; Newer Posts</a>
    </div>

    <div class="px-1">
        <a class="btn btn-primary <%= pageIncrement == 0 ? 'disabled' : '' %>" href="/?page=<%= currPage + pageIncrement %>">Older Posts &rarr;</a>
    </div>
  </div>
<% } %>

问题

来自控制器的行 .limit(perPage) 在控制台中给出了错误 perPage is not defined (Git bash)。

无效的解决方案

显然,我可以将这两行移到上面 const posts

const perPage = 5;
const currPage = req.query.page ? parseInt(req.query.page) : 1;

但我不能const postsCount = posts.length;做同样的事情(我在视图中也需要)。

objective

我正在尝试制作有关分页的代码片段 可重复使用 (如果可能的话,就像一个插件),因为我需要为 post 分页按类别过滤,以及应用程序管理部分中的 post 列表。

我做错了什么?

正如评论正确指出的那样,这似乎是一个范围界定问题。

exports.getPosts = async (req, res, next) => {
  // getPosts local scope
  const posts = await Post.find({}, (err, posts) => {
      // ... local scope
      const perPage = 10;

      const currPage = req.query.page ? parseInt(req.query.page) : 1;

      const postsCount = posts.length;

      const pageCount = Math.ceil(postsCount / perPage);

      const pageDecrement = currPage > 1 ? 1 : 0;

      const pageIncrement = currPage < pageCount ? 1 : 0;

      if (err) {
        console.log("Error: ", err);
      } else {
        res.render("default/index", {
          moment: moment,
          layout: "default/layout",
          website_name: "MEAN Blog",
          page_heading: "XPress News",
          page_subheading: "A MEAN Stack Blogging Application",
          currPage: currPage,
          pageDecrement: pageDecrement,
          pageIncrement: pageIncrement,
          posts: posts,
        });
      }
      // ... local scope ended
    })
      .sort({ created_at: -1 })
      .populate("category")
      // perPage == undefined
      .limit(perPage)
      .skip(currPage - 1)) * perPage;
};

const perPage 移动到 const posts 上方,它将在正确的 scope/context.

范围内
exports.getPosts = async (req, res, next) => {
  const perPage = 10;
  // getPosts local scope
  const posts = await Post.find({}, (err, posts) => {
      // ... rest of func
    });
  // .. rest of func
};

也许如果你检查这个组件,你可以通过查看它的工作原理来解决你的问题

Mongoose Paginate

$ npm install mongoose-paginate

/**
* querying for `all` {} items in `MyModel`
* paginating by second page, 10 items per page (10 results, page 2)
**/

MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
 if (error) {
   console.error(error);
 } else {
   console.log('Pages:', pageCount);
   console.log(paginatedResults);
 }
}

如其他评论所述。这可能只是范围的问题。

exports.getPosts = async (req, res, next) => {
  const perPage = 10; // enable you to use perPage inside getPosts()
  let postsCount = 0; // let, to enable you to use/reassigned postsCount inside getPosts()
  const posts = await Post.find({}, (err, posts) => {
    // ...
    postsCount = posts.length; // updates the variable with the correct count
    // ...
    if (err) {
        console.log("Error: ", err);
      } else {
        res.render("default/index", {
          //...
          posts: posts,
          postsCount: posts.length, // for explicit postsCount in the view

        });
      }

  });

  // ..


对于视图中的 postsCount 问题,因为您的视图中已经有 posts

<% if (posts) {%>
  ...
<% } %>

我认为您可以在视图中使用 posts.lengthpostsCounts,就像使用其他视图一样(例如 pageIncrement、currPage、pageIncrement);

你为什么要使用回调和等待 together.seems 就像你需要查看 async / await 和 promises.What 你可以做的如下:

exports.getPosts = async (req, res, next) => {
  const currPage = req.query.page ? parseInt(req.query.page) : 1;
  const perPage = 10;
  try {
    const posts = await Post.find({})
      .sort({ created_at: -1 })
      .populate("category")
      .limit(perPage)
      .skip((currPage - 1) * perPage).exec();

    const postsCount = posts.length;

    const pageCount = Math.ceil(postsCount / perPage);

    const pageDecrement = currPage > 1 ? 1 : 0;

    const pageIncrement = currPage < pageCount ? 1 : 0;
    res.render("default/index", {
      moment: moment,
      layout: "default/layout",
      website_name: "MEAN Blog",
      page_heading: "XPress News",
      page_subheading: "A MEAN Stack Blogging Application",
      currPage: currPage,
      pageDecrement: pageDecrement,
      pageIncrement: pageIncrement,
      posts: posts,
    });
  } catch (err) {
    console.log("Error: ", err);
    // add proper error handling here 
    res.render('default/error', {
      err
    });
  }
};

正如我最近发现的 postsCount = posts.length 计算 之后的帖子,它们受到 .skip((currPage - 1) * perPage) 的限制,所以 pageIncrement 变量 "equation" 变为:

let pageIncrement = postsCount >= perPage ? 1 : 0;

所以我在控制器中得到:

exports.getPosts = async (req, res, next) => {

    const perPage = 5;

    const currPage = req.query.page ? parseInt(req.query.page) : 1;

    let postsCount = 0;

    const posts = await Post.find({}, (err, posts) => {

            postsCount = posts.length;

            let pageDecrement = currPage > 1 ? 1 : 0;

            let pageIncrement = postsCount >= perPage ? 1 : 0;

            if (err) {
                console.log('Error: ', err);
            } else {
                res.render('default/index', {
                    moment: moment,
                    layout: 'default/layout',
                    website_name: 'MEAN Blog',
                    page_heading: 'XPress News',
                    page_subheading: 'A MEAN Stack Blogging Application',
                    currPage: currPage,
                    posts: posts,
                    pageDecrement: pageDecrement,
                    pageIncrement: pageIncrement
                });
            }
        })
        .sort({
            created_at: -1
        })
        .populate('category')
        .limit(perPage)
        .skip((currPage - 1) * perPage);
};

并且在视图中:

<a class="btn btn-primary <%= pageDecrement == 0 ? 'disabled' : '' %>" href="/?page=<%= currPage - pageDecrement %>">&larr; Newer Posts</a>

<a class="btn btn-primary <%= pageIncrement == 0 ? 'disabled' : '' %>" href="/?page=<%= currPage + pageIncrement %>">Older Posts &rarr;</a>

除非帖子数量等于 perPage x N,其中 N 是一个整数,在这种情况下,"Older Posts" 按钮被禁用的时间就晚了一页。