Model.find().toArray() claiming to not have .toArray() method

梦想的初衷 提交于 2019-11-26 17:51:35

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.

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

Then, to call it:

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 */);

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

You should utilize the callback of find:

var userBlogs = function(username, next) {
    Blog.find({author: username}, function(err, blogs) {
        if (err) {
            ...
        } else {
            next(blogs)
        }
    })
}

Now you can get your blogs calling this function:

userBlogs(username, function(blogs) {
   ...
})

Try something along the lines of:

Blog.find({}).lean().exec(function (err, blogs) {
  // ... do something awesome... 
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!