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

查看:30
本文介绍了Model.find().toArray() 声称没有 .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('/');
  });
});

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

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 函数存在于来自 Native MongoDB NodeJS 驱动程序(参考).MongooseJS 中的 find 方法返回一个 Query 对象(参考).有几种方法可以进行搜索并返回结果.

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 的示例,通常在 JavaScript 中使用 MongoDB 控制台意味着本机驱动程序也支持类似的功能,但它不支持.

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}).

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

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