Mongodb ejs 模板中的游标为空(ejs 中的异步调用)
Mongodb cursor is empty in ejs template(Async call inside ejs )
以下路由器调用 ejs 模板将光标的值填充到 html 页面。
router.get('/users_loaded_disconnect', function(req, res) {
res.render('users_loaded_disconnect',
{cursor: req.db.collection('notify_user_state_collection').find({})});
});
user_loaded_disconnect.ejs
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<b> Users Loaded Disconnect </b>
<ul>
<% cursor.nextObject(function(err, item) { %>
<%= JSON.stringify(item) %>
<% }); %>
</ul>
</body>
</html>
光标不起作用。但是,如果光标像下面的代码一样在路由器中迭代,它会打印值
req.db.collection('notify_user_state_collection').find({}).nextObject(function(err, item) {
console.log(JSON.stringify(item));
});
在 ejs 模板中迭代游标有什么问题?
游标操作是异步的。 Ejs 不会等待它完成,会在数据可用之前继续渲染模板。您无法在 ejs 模板中有效地使用回调。
以下路由器调用 ejs 模板将光标的值填充到 html 页面。
router.get('/users_loaded_disconnect', function(req, res) {
res.render('users_loaded_disconnect',
{cursor: req.db.collection('notify_user_state_collection').find({})});
});
user_loaded_disconnect.ejs
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<b> Users Loaded Disconnect </b>
<ul>
<% cursor.nextObject(function(err, item) { %>
<%= JSON.stringify(item) %>
<% }); %>
</ul>
</body>
</html>
光标不起作用。但是,如果光标像下面的代码一样在路由器中迭代,它会打印值
req.db.collection('notify_user_state_collection').find({}).nextObject(function(err, item) {
console.log(JSON.stringify(item));
});
在 ejs 模板中迭代游标有什么问题?
游标操作是异步的。 Ejs 不会等待它完成,会在数据可用之前继续渲染模板。您无法在 ejs 模板中有效地使用回调。