该
toArray函数存在于本
Cursor机MongoDB
NodeJS驱动程序的类(参考)上。
findMongooseJS中的方法返回一个
Query对象(reference)。您可以通过几种方式进行搜索并返回结果。
由于MongoDB的NodeJS驱动程序中没有同步调用,因此在所有情况下都需要使用异步模式。MongoDB的示例(通常在Java中使用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) { return; } // do something with the blogs here ... res.redirect('/');});您还可以对字段进行排序(例如,博客发布日期):
Blog.find().where("author", username). sort("-postDate").exec();上面的代码将基于名为
postDate(备用语法:的字段)降序排列
sort({ postDate: -1})。


