猫鼬发现结果不刷新

mongoose find results not refreshing

我正在与 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}

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

每次调用 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
    ...
  }
});

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