2017-12-14 4 views
0

나는 다음과 같은 스키마가 : 나는 쿼리 할 때는 조건부로 몽고 쿼리 경로를 채우는

const connectionSchema = new Schema({ 
    ... 
    event: { 
    type: Schema.ObjectId, 
    ref: 'events' 
    }, 
    place: { 
    type: Schema.ObjectId, 
    ref: 'places' 
    }, 
}) 

const eventsSchema = new Schema({ 
    ... 
    place: { 
    type: Schema.ObjectId, 
    ref: 'places' 
    }, 
}) 

어느 하나의 connection 또는 connection s의 수집, 나는 event가 지정된 경우 그것을 확인하고 싶은 경우를 따라서 event에서 place을 반품하고, 그렇지 않은 경우 에서 place을 반환하십시오.

내가 단일 연결 쿼리있을 때 나는 현재 이런 일을하고 있어요

: 나는 대체 수행 할 execFunction에 전체 컬렉션을 반복하는 것을 피하기 위해 노력하고있어,

let c 
const execFunction = (err, connection) => { 
    if (connection.event) { 
    connection.place = connection.event.place 
    } 
    c = connection 
} 

const connectionPromise = Connection.findById(connectionId) 
connectionPromise.populate({ path: 'event', populate: { path: 'place' } }) 
connectionPromise.populate('place') 
connectionPromise.exec(execFunction) 

을하지만, 대신 컬렉션을 쿼리하면 각 개별 결과에 대한 논리가됩니다.

더 좋은 (즉 더 뛰어난) 방법이 있습니까?

+1

엄밀히 말하면, 그것은 .exec() 또는 .then()입니다. 그때까지,'connectionPromise'는 실제로 쿼리입니다! #namingthings – joeytwiddle

+0

@joeytwiddle 아 네, 지적 해 주셔서 고마워요. –

답변

0

내가 아는 한, 몽구스로 조건부 인구를 할 방법이 없습니다.

당신의 경우에, 나는 당신이 "깊은 인구"를하려고 노력하고 있다고 생각합니다.

딥 (deep) 인구 분포는 기본적으로 지원되지 않지만 플러그인은 있습니다! 'event'는 암시한다 : mongoose-deep-populate

const connectionQuery = Connection.findById(connectionId) 
connectionQuery.populate('place event event.place') 
connectionQuery.exec(execFunction); 

나는 'place event.place' 아마 그것을 할 것 같은데요.

또한 place 또는 event 또는 이 정의되지 않은 경우 오류가 발생하지 않으며 단순히 채워지지 않을 것으로 예상됩니다.

그러나 event.place을 사용할 수있는 경우 한 줄에 place을 채우는 것을 건너 뛰는 방법은 없다고 생각합니다.

return Connection.findById(connectionId) 
    .populate('place event event.place') 
    .then(onSuccessFunc); 

오류를 전파, 또는 : 당신이 약속을 사용하려면 그런데


, 당신은 다음과 같이 쓸 수

Connection.findById(connectionId) 
    .populate('place event event.place') 
    .then(onSuccessFunc) 
    .catch(onErrorFunc); 

로컬 오류를 처리 할 수 ​​있습니다. 우리는 모든 단계에서 if (err)에 대해 걱정할 필요가 없기 때문에 콜백보다 바람직하다고 생각합니다.