【问题标题】:mongoose find results not refreshing猫鼬发现结果不刷新
【发布时间】:2019-04-12 10:04:28
【问题描述】:

我正在使用 express/jade/mongodb 创建一个带有数据库的站点(在这方面很新)。 我在使用此函数的 get 方法期间使用“mongoose find”从数据库中检索列表:

function getBookList(Book, req, callback){
  Book.find({'username': req.user.username}, 'bookTitle author', function(err, userBooks) {
    if (err) return handleError(err);
    else if (userBooks.length > 0) {
      bookList.push(userBooks);
      callback();
    }
  });
};

router.get('/', ensureAuthenticated, function(req, res, next) {
 getBookList(Book, req, function(){
      res.locals.user.books = bookList[0];
      res.render('index', { title: 'library' });
  });
});

在我的jade文件中,代码是:

ul
    each book in user.books
        li #{book.bookTitle}
            span  -  
            span #{book.author}

第一次使用用户登录时,我按预期获得了列表,但如果我将文档添加到数据库并再次呈现页面,我页面上的列表不会更新并保持原样。 即使在注销和再次登录后,它也保持不变。只有在重新启动服务器后,列表才会更新。 谁能向我解释我做错了什么?

【问题讨论】:

    标签: node.js mongodb express mongoose pug


    【解决方案1】:

    对于getBookList 的每次调用,您都将生成的书籍数组推入另一个数组bookList

    假设您在数据库中有一个文档并调用getBookList。之后,bookList 将如下所示:

    bookList = [ [ 'book 1' ] ]
    

    然后您添加另一本书,并再次致电getBookList。现在bookList 看起来像这样:

    bookList = [ [ 'book 1' ], [ 'book 1', 'book 2' ] ]
    

    但是,您只使用过bookList[0],因此是第一次调用getBookList 的结果。这永远不会包含新文档,因为它们只会出现在bookList 的后续条目中。

    但这不是要解决的最大问题,因为您使用 bookList 作为全局变量,这不是一个好主意。相反,getBookList 应该将书籍列表传回给调用者。

    这将使代码看起来像这样:

    function getBookList(username, callback){
      Book.find({'username': username}, 'bookTitle author', function(err, userBooks) {
        callback(err, userBooks);
      });
    };
    
    router.get('/', ensureAuthenticated, function(req, res, next) {
     getBookList(req.user.username, function(err, userBooks) { 
      if (err) return handleError(err);
      else if (userBooks.length > 0) {
        res.locals.user.books = userBooks;
        res.render('index', { title: 'library' });
      } else {
        // handle the situation where no books were found
        ...
      }
    });
    

    还有一些其他变化,例如将 getBookList 从模型 (Book) 和请求 (req) 中解耦。

    【讨论】:

      猜你喜欢
      • 2016-02-04
      • 2014-05-30
      • 2013-11-01
      • 2015-08-26
      • 2018-08-22
      • 2018-09-30
      • 2023-03-26
      • 2017-11-07
      相关资源
      最近更新 更多