Model.find().toArray()声称没有.toArray()方法

Ror*_*120 10 mongoose mongodb node.js passport.js pug

我是nodejs和mongodb的新手,我正在尝试拼凑我自己的博客应用程序.我在尝试通过我的"博客"模型查询具有特定用户名的模型时遇到问题.当我试图跑

var userBlogs = function(username) {
  ub = Blog.find({author: username}).toArray();
  ub = ub.reverse();
};
Run Code Online (Sandbox Code Playgroud)

我收到一个错误.

TypeError: Object #<Query> has no method 'toArray'
Run Code Online (Sandbox Code Playgroud)

我知道全局变形很糟糕,但我一直试图让它起作用.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);
Run Code Online (Sandbox Code Playgroud)

这是/ 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('/');
  });
});
Run Code Online (Sandbox Code Playgroud)

最终的结果应该适用于这个玉:

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
Run Code Online (Sandbox Code Playgroud)

如何获取查询以输出数组,甚至可以作为对象?

Wir*_*rie 8

toArray函数存在于CursorNative MongoDB NodeJS驱动程序(引用)的类中.findMongooseJS中的方法返回一个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);
          });
};
Run Code Online (Sandbox Code Playgroud)

然后,打电话给它:

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('/');
});
Run Code Online (Sandbox Code Playgroud)

您还可以对字段进行排序(例如博客发布日期):

Blog.find().where("author", username).
   sort("-postDate").exec(/* your callback function */);
Run Code Online (Sandbox Code Playgroud)

上面的代码将根据调用的字段按降序排序postDate(替代语法:sort({ postDate: -1}).