声称没有.toArray()方法的Model.find().toArray() [英] Model.find().toArray() claiming to not have .toArray() method

查看:120
本文介绍了声称没有.toArray()方法的Model.find().toArray()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Node.js和MongoDB还是陌生的,并且正在尝试组装自己的博客应用程序.我在尝试通过博客"模型查询具有特定用户名的用户时遇到问题.当我尝试运行时:

I am very new to Node.js and MongoDB and am trying to piece together my own blogging application. I have a problem trying to query through my 'Blog' model for ones with a specific username. When I try to run:

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

我得到一个错误:

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

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

I know globals are bad but I've just been trying to get it to work. The Mongo documentation claims that a cursor is returned which can have the toArray() method called on it. I have no idea why it won't work.

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

Here is my schema/model creation:

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请求

Here are the /login and /readblog requests

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

最终的结果应该与这个翡翠一起使用:

The end result is supposed to work with this 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

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

How can I get the query to output an array, or even work as an object?

推荐答案

toArray函数存在于本机MongoDB NodeJS驱动程序(参考) .您可以通过几种方式进行搜索并返回结果.

The toArray function exists on the Cursor class from the Native MongoDB NodeJS driver (reference). The find method in MongooseJS returns a Query object (reference). There are a few ways you can do searches and return results.

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

As there are no synchronous calls in the NodeJS driver for MongoDB, you'll need to use an asynchronous pattern in all cases. Examples for MongoDB, which are often in JavaScript using the MongoDB Console imply that the native driver also supports similar functionality, which it does not.

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

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

You could also do sorting on a field (like a blog post date for example):

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

上面的代码将基于称为postDate的字段以降序排列(替代语法:sort({ postDate: -1}).

The above code would sort in descending order based on a field called postDate (alternate syntax: sort({ postDate: -1}).

这篇关于声称没有.toArray()方法的Model.find().toArray()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆