我正在将MongoDB与Express结合使用来制作一个简单的Web应用程序。我正在尝试从集合中获取单个文档,但是查询运行了3次。我已经尝试过find和findOne,但两者都给我相同的结果。另外,不确定是否相关,这是唯一不提供Express应用程序中的部分模板和公用文件夹的页面。这是特定路线的代码
app.get('/interview/:name', (req, res) => {
// Get the interview from the database
let username = req.params.name.replace(/:/, '');
db.collection('interviews-test').find({'username' : username}).sort({$natural:-1}).limit(1).toArray(function(err, result){
if (err) return console.log(err); // Check for errors
console.log(result);
res.render('interview.ejs', {interview: result, renderedHTML: convertMarkdown(result[0].interview)});
});
});
这是console.log
[ { _id: 5b375cdf4053382124afa6c9,
title: 'Testing interview titles',
username: 'usertet',
interview: '# Welcome to StackEdit!\r\n\r\nHi! I'm your first Markdown file in **StackEdit**. If you want to learn about StackEdit, you can read me. If you want to play with Markdown, you can edit me. If you have finished with me, you can just create new files by opening the **file explorer** on the left corner of the navigation bar.\r\n\r\n\r\n# Files\r\n\r\nStackEdit stores your files in your browser, which means all your files are automatically saved locally and are accessible **offline!**\r\n\r\n## Create files and folders\r\n\r\nThe file explorer is accessible using the button in left corner of the navigation bar. You can create a new file by clicking the **New file** button in the file explorer. You can also create folders by clicking the **New folder** button.\r\n\r\n## Switch to another file\r\n\r\nAll your files are listed in the file explorer. You can switch from one to another by clicking a file in the list.',
created: '30 Jun 2018' } ]
[]
[]
C:\Users\Mascarell\Desktop\freelance-tips\node_modules\mongodb\lib\utils.js:132
throw err;
^
TypeError: Cannot read property 'interview' of undefined
它确实返回了数据,但是又返回了两次,但结果没有定义。
感谢阅读,希望有人能帮助我!