2012-08-23 3 views
5

nodejs의 컬렉션을 통해 다른 ID를 반복하려고합니다. 다음 코드와 같이 일하는 것이 뭔가 :Mongoose - 다음 요소로 이동

//Callbacks removed for readability 

var thisPost = mongoose.model('Post').findOne({tags: 'Adventure'}); 
console.log(thisPost.title); // 'Post #1 - Adventure Part 1' 

var nextPost = thisPost.next({tags: 'Adventure'); 
console.log(nextPost.title); // 'Post 354 - Adventure Part 2' 

최고의 아이디어 지금까지 내가 전화를 찾을 수 있도록 특정 ID에 내 옆에있는 참조를 통해() 내 스키마에 LinkedList의를 추가하는 것입니다하지만 난 뭔가를 기대했다 덜 복잡하기 때문에이 Mongoose 참조 (thisPost)를 커서로 사용하여 find()를 시작할 수 있습니다.

감사합니다.

EDIT : 반복은 여러 페이지 쿼리를 처리하기위한 것입니다. 더 나은 예 :

//Callbacks removed for readability 

//User 'JohnDoe' visits the website for the first time 
var thisQuote = mongoose.model('Quote').findOne().skip(Math.rand()); 
res.send(thisQuote); // On page output, JohnDoe will see the quote 42 
//Saving the current quote cursor to user's metadatas 
mongoose.model('User').update({user: 'JohnDoe'}, {$set: {lastQuote: thisQuote }}); 

//User 'JohnDoe' comes back to the website 
var user = mongoose.model('User').findOne({user: 'JohnDoe}); 
var thisQuote = user.lastQuote.next(); 
res.send(thisQuote); // On page output, JohnDoe will see the quote 43 
//Saving the current quote cursor to user's metadatas 
mongoose.model('User').update({user: 'JohnDoe'}, {$set: {lastQuote: thisQuote }}); 

//And so on... 

답변

11
당신은 몽구스의 스트리밍 기능으로 보일 수 있습니다

:

var stream = mongoose.model('Post').find({tags: 'Adventure'}).stream(); 

// Each `data` event has a Post document attached 
stream.on('data', function (post) { 
    console.log(post.title); 
}); 

QueryStream, 당신이 경우 pauseresume를 사용하여 몇 가지 흥미로운 작업을 수행 할 수 있도록 stream() 반환, Node.js' Stream에서 상속 것입니다 필요하다.

[편집] 지금은 좀 더 귀하의 질문을 이해

, 나는 QueryStream 아마 하지 사용할 무엇이라고 말할 것입니다. 나는 오늘 이것에 약간 일하고 https://gist.github.com/3453567에 일하는 해결책을 얻었다; 요지 (git://gist.github.com/3453567.git)를 복제하고 npm install을 실행 한 다음 node index.js을 실행하면 http://localhost:3000으로 사이트를 방문 할 수 있습니다. 페이지를 새로 고침하면 "다음"인용 부호가 나타나야하고 마지막에 도달하면 둘러 볼 수 있습니다.

이 때문에 몇 가지의 작동 :

첫째, 우리는 데이터에서 사용자의 "마지막으로 본"따옴표에 reference을 저장 : 이제

var UserSchema = new mongoose.Schema({ 
    user: String, 
    lastQuote: { type: mongoose.Schema.Types.ObjectId, ref: 'Quote' } 
}); 

우리가 User.findOne().populate('lastQuote')를 수행 lastQuote 속성 반환 된 사용자의 MongoDB (ObjectId)에 저장된 필드의 값으로 참조되는 실제 Quote 객체가됩니다.

때문에 우리는 다음과 같은 코드의 견적 객체에 next()를 호출 할 수

QuoteSchema.methods.next = function(cb) { 
    var model = this.model("Quote"); 
    model.findOne().where('_id').gt(this._id).exec(function(err, quote) { 
    if (err) throw err; 

    if (quote) { 
     cb(null, quote); 
    } else { 
     // If quote is null, we've wrapped around. 
     model.findOne(cb); 
    } 
    }); 
}; 

이 다음 견적을 찾거나 다른 첫 번째 따옴표로 감싸는 부분입니다.

코드를보고 궁금한 점이 있으면 알려주십시오.

+0

마지막으로이 버전을 사용하지 않았지만 설명서에서 볼 때 스트림이 내가 원하는 것을 수행하는 가장 좋은 방법입니다. 비록 내 애플 리케이션의 현재 코드 아키텍처에 의존 많은 이유로 그것을 사용하지 않을거야 :) – red

+0

나는 내 대답을 기반으로 귀하의 업데이 트를 수정했습니다. –

+0

와우. 어제 데이터베이스에 링크 된 목록을 사용하여 구현했지만 답변이 너무 간단합니다. 직접 생각하지 않으면 부끄럽습니다. 당신의 생각에 대한 명성과 백만 분의 응답을 주셔서 감사합니다 :) – red

관련 문제