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

2023-05-01 13:48

该@H_404_1@toArray函数存在于本@H_404_1@Cursor机MongoDB NodeJS驱动程序的类(参考)上。@H_404_1@findMongooseJS中的方法返回一个@H_404_1@Query对象(reference)。您可以通过几种方式进行搜索并返回结果。

由于MongoDB的NodeJS驱动程序中没有同步调用,因此在所有情况下都需要使用异步模式。MongoDB的示例(通常在Java中使用MongoDB控制台使用JavaScript)暗示本机驱动程序也支持类似的功能,而事实并非如此。

@H_404_1@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);
          });
};

然后,调用它:

@H_404_1@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('/');
});

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

@H_404_1@Blog.find .where("author", username).
   sort("-postDate").exec(/* your callback function */);

上面的代码将基于名为@H_404_1@postDate(备用语法:的字段)降序排列@H_404_1@sort({ postDate: -1})。

解决方法

我是Node.js和MongoDB的新手,正在尝试组装自己的博客应用程序。我在尝试通过“博客”模型查询具有特定用户名的用户时遇到问题。当我尝试运行时:

var userBlogs = function(username) {
  ub = Blog.find({author: username}).toArray ;
  ub = ub.reverse ;
};

我收到一个错误:

TypeError: Object #<Query> has no method 'toArray'

我知道全局变量不好,但是我一直在努力使其正常运行。Mongo文档声称返回了一个游标,该游标可以具有toArray 调用的方法。我不知道为什么它不起作用。

这是我的架构/模型创建:

var blogSchema = mongoose.Schema({
  title: {type:String,required: true},author: String,content: {type:String,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',res){
  res.render('login',{ user: req.user,message: req.session.messages });
});

app.post('/login',passport.authenticate('local',{ failureRedirect: '/login'}),res) {
    userBlogs(req.user.username);
    res.redirect('/');
  });
});

最终结果应该与这个Jade一起使用:

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

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