MongoDB游标在ejs模板中是空的(asynchronous调用内部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模板中的游标有什么错误?
游标操作是asynchronous的。 Ejs不会等待它完成,并会在数据可用之前继续渲染模板。 你不能有效地在ejs模板中使用callback。