복붙노트

[MONGODB] Model.find (). toArray () .toArray이없는 주장 () 메소드

MONGODB

Model.find (). toArray () .toArray이없는 주장 () 메소드

나는 Node.js를하고 MongoDB를 매우 새로운 오전과 함께 내 자신의 블로그 응용 프로그램을 조각하려합니다. 나는 문제가 특정 사용자 이름을 가진 것들에 대한 내 '블로그'모델을 통해 쿼리에 노력하고 있습니다. 언제 실행하려고 :

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

오류가 발생합니다 :

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

나는 전역 나쁜 알고 있지만 난 그냥 일을 얻기 위해 노력했습니다. 커서가에서 호출 된 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);

여기에 / 로그인 및 / 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('/');
  });
});

최종 결과는이 옥에서 작동하도록되어있다 :

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

어떻게 출력 쿼리를 대상으로 배열, 또는 일을받을 수 있나요?

해결법

  1. ==============================

    1.toArray 함수 네이티브 MongoDB를 NodeJS 드라이버 (참조)의 커서 클래스에 존재한다. MongooseJS에서 찾기 방법은 쿼리 객체 (참조)를 반환합니다. 당신은 검색 및 리턴 결과를 할 수있는 몇 가지 방법이 있습니다.

    toArray 함수 네이티브 MongoDB를 NodeJS 드라이버 (참조)의 커서 클래스에 존재한다. MongooseJS에서 찾기 방법은 쿼리 객체 (참조)를 반환합니다. 당신은 검색 및 리턴 결과를 할 수있는 몇 가지 방법이 있습니다.

    MongoDB를위한 NodeJS 드라이버에는 동기 호출이없는, 당신은 모든 경우에 비동기 패턴을 사용해야합니다. 자바 스크립트가 MongoDB의 콘솔을 사용하여 종종 MongoDB를위한 예를 들면, 기본 드라이버는 또한하지 않는, 유사한 기능을 지원하는 것을 의미한다.

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

    당신은 또한 (예를 들어, 블로그 게시물의 날짜와 같은) 필드에 정렬 할 수 있습니다 :

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

    위의 코드는 정렬 순서를 내림차순으로 시간적으로 (대체 구문이라는 필드를 기준으로 다음과 같습니다 종류 ({시간적으로 : -1}).

  2. ==============================

    2.당신은 발견의 콜백을 사용한다 :

    당신은 발견의 콜백을 사용한다 :

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

    지금 당신은이 함수를 호출 블로그를 얻을 수 있습니다 :

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

    3.의 라인을 따라 뭔가를보십시오 :

    의 라인을 따라 뭔가를보십시오 :

    Blog.find({}).lean().exec(function (err, blogs) {
      // ... do something awesome... 
    } 
    
  4. from https://stackoverflow.com/questions/20858299/model-find-toarray-claiming-to-not-have-toarray-method by cc-by-sa and MIT license