2016-07-18 2 views
3

저는 노드와 몽구스를 사용하는 초보 개발자이며 몽구스로 쿼리를 연결하는 가장 좋은 방법이 무엇인지 궁금합니다. 나는 아래처럼 행동하고있다.몽구스 쿼리를 연결하는 가장 좋은 방법

User.findByIdAndUpdate(req.params._id, user, { upsert: true }) 
.exec((err, updatedUser) => { 
    if (addedCollections) { 
    return User.findByIdAndUpdate(req.params._id, { $push: { _collections: { $each: addedCollections } } }, { upsert: true }).exec(); 
    } 
    return new Query; 
}) 
.exec(() => { 
    return User.findById(req.params._id).populate('_collections'); 
}) 
.exec((err, user) => { 
    res.json({ user }); 
}) 

어떻게 체인 여러 쿼리를 할 수 있습니까?

User.findByIdAndUpdate(req.params._id, user, { upsert: true }) 
    .then(updatedUser => { 
     if (addedCollections) { 
     return User.findByIdAndUpdate(req.params._id, { $push: { _collections: { $each: addedCollections } } }, { upsert: true }); 
     } 
    }) 
    .then(() => { 
     return User.findById(req.params._id).populate('_collections'); 
    }) 
    .then(user => { 
     res.json({ user }); 
    }) 
    .catch(err => { 
     res.status(500).json({ error : err }); 
    }); 

답변

5

당신은 당신이 뭘 하려는지 꽤 비슷 약속 체인을 사용할 수 있습니다. Rx의 경우 .flatMap()은 .then()과 같습니다. https://www.npmjs.com/package/mongoose-observables

에서

var Rx = require('rx'); 
var observables = require('mongoose-observables'); 

/* get public header data, list of collections and projects */ 

router.get("/header", function(req, res) { 
    let articleTitle = observables.finder.find(Articles, '{}', ['title'], null); 
    let collectionTitle = observables.finder.find(Collections, '{}', ['title'], null); 

    Rx.Observable.forkJoin([articleTitle, collectionTitle]) 
    .subscribe(
     (docs) => res.json(docs), 
     (err) => console.error(err) 
    ); 
}); 

추가 예

0

당신은 수신 및 몽구스 - 관찰 가능한을 사용할 수 있습니다

관련 문제