find after populate mongoose
Post

find after populate mongoose

User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const userSchema = mongoose.Schema({
    name: {
        type: String,
        maxlength: 50
    },
    email: {
        type: String,
        trim: true
    },
    depart: {
        type: Schema.Types.ObjectId,
        ref: 'Depart'
    }
}

Depart

1
2
3
4
5
6
7
8
const departSchema = mongoose.Schema({
    departCode: {
        type: String
    },
    departName: {
        type: String
    }
})

사용자 검색 시 특정 부서코드를 검색하여 찾기

populate 시 검색 조건 {departCode:’1000’} 을 입력 후 user.depart가 있는 항목만 필터링 한다.

1
2
3
4
5
6
7
8
  User
    .find({name:'홍길동'})
    .populate("depart", {departName: 1, departCode: 2}, {departCode:'1000'})
    .exec(function(err, result) {
        if (err) return next(err)
      result = result.filter(user => {return user.depart})  
    })
  });