我是nodejs和mongodb的新手,我正在尝试拼凑我自己的博客应用程序.我在尝试通过我的"博客"模型查询具有特定用户名的模型时遇到问题.当我试图跑
var userBlogs = function(username) { ub = Blog.find({author: username}).toArray(); ub = ub.reverse(); };
我收到一个错误.
TypeError: Object #has no method 'toArray'
我知道全局变形很糟糕,但我一直试图让它起作用.Mongo文档声称返回了一个游标,可以在其上调用toArray()方法.我不知道为什么它不起作用.这是我的架构/模型创建:
var blogSchema = mongoose.Schema({ title: {type:String, required: true}, author: String, content: {type:String, required: true}, timestamp: String }); var Blog = mongoose.model('Blog', blogSchema);
这是/ login和/ readblog请求
app.get('/readblog', ensureAuthenticated, function(req, res) { res.render('readblog', {user: req.user, blogs: ub}) }) app.get('/login', function(req, res){ res.render('login', { user: req.user, message: req.session.messages }); }); app.post('/login', passport.authenticate('local', { failureRedirect: '/login'}), function(req, res) { userBlogs(req.user.username); res.redirect('/'); }); });
最终的结果应该适用于这个玉:
extends layout block content if blogs for blog in blogs h2= blog[title] h4= blog[author] p= blog[content] h4= blog[timestamp] a(href="/writeblog") Write a new blog
如何获取查询以输出数组,甚至可以作为对象?
该toArray
函数存在于Cursor
Native MongoDB NodeJS驱动程序(引用)的类中.find
MongooseJS中的方法返回一个Query
对象(参考 e).您可以通过多种方式进行搜索并返回结果.
由于MongoDB的NodeJS驱动程序中没有同步调用,因此在所有情况下都需要使用异步模式.MongoDB的示例(通常使用MongoDB控制台的JavaScript)意味着本机驱动程序也支持类似的功能,但实际上并非如此.
var userBlogs = function(username, callback) { Blog.find().where("author", username). exec(function(err, blogs) { // docs contains an array of MongooseJS Documents // so you can return that... // reverse does an in-place modification, so there's no reason // to assign to something else ... blogs.reverse(); callback(err, blogs); }); };
然后,打电话给它:
userBlogs(req.user.username, function(err, blogs) { if (err) { /* panic! there was an error fetching the list of blogs */ return; } // do something with the blogs here ... res.redirect('/'); });
您还可以对字段进行排序(例如博客发布日期):
Blog.find().where("author", username). sort("-postDate").exec(/* your callback function */);
上面的代码将根据调用的字段按降序排序postDate
(替代语法:sort({ postDate: -1})
.