2017-11-27 7 views
0

방법이 명 컬렉션을 포함하는 쿼리에서 데이터를 얻을 수 있습니다. 내가하는 일, 고객에 대한 쿼리를 실행해야다른 컬렉션의 문서를 채우는 방법. <strong>고객</strong> 및 <strong>주소</strong></p> I 고객 컬렉션에 쿼리, 그들 모두에 대한 모든 주소를 모든 고객을 얻을 필요가 <p>: 특정 경우

var Addresscustomer = require ('./addresscustomer'); 

var Schema = mongoose.Schema; 

var customerSchema = Schema({ 
    name: { 
     type: String, 
     required: false, 
     unique: false 
    }, 
    address: { 
     type: Array, 
     ref: 'Addresscustomer' 
    } 
}, { 
    timestamps: true 
}); 

module.exports = mongoose.model('Customer', customerSchema, 'customers'); 

:

addressescustomers :

var Customer = require('./customer'); 

var Schema = mongoose.Schema; 

var addressSchema = Schema({ 
    address: { 
     type: String, 
     required: false, 
     unique: false 
    }, 
    customer: { 
     type: Schema.Types.ObjectId, 
     ref: 'Customer' 
    } 
}, { 
    timestamps: true 
}); 

module.exports = mongoose.model('Addresscustomer', addressSchema, 'addressescustomers'); 

고객이를 몽구스 사용

는 2 스키마입니다 이것입니다 :

Customer.find({}, function (err, customers) { 
      Addresscustomer.populate(customers, { path: "address" }, function (err, customers) { 
       console.log('Customers: '+ customers); 
      }); 
     }); 

또는 :

var query = Customer.find({}).populate('address'); 
query.exec(function (err, customers) { 
     console.log('Customers: '+ customers); 
    }); 

그러나 고객 컬렉션에서 키 주소이 작성되지 않았습니다. 정확한 데이터를 얻기 위해 스키마와 쿼리를 올바르게 설정하는 방법을 알려주시겠습니까?

+1

가능한 복제 (https://stackoverflow.com/questions/9621928/how-do-i-query-referenced-objects-in-mongodb) – sidgate

+0

@sidgate 그것은 중복이 아니며 올바른 참조는 다음과 같은 주소 고객에 있습니다. type : Schema.Types.ObjectId, ref : '고객'} 주소 고객이 아닌 customers 컬렉션에서 쿼리를 수행해야하지만 한 고객은 많은 주소를 가지고 있습니다. 몽구스 인구()와 함께 할 수 있습니까? – Carlos

답변

1

$lookup을 사용하여 주소 참조를 채울 수 있습니다. 이후 Mongo 3.4 $ 배열도 works을 조회합니다.

db.customers.aggregate([ 
    { "$lookup": { 
     "from": "addressescustomers", 
     "localField": "address", 
     "foreignField": "_id", 
     "as": "addr" 
    }} 
]) 
[내가 MongoDB의에서 참조 된 개체를 조회하려면 어떻게?]의
+0

내 구체적인 경우에도이 솔루션은 다음과 같습니다. db.customers.aggregate ( { "$ lookup": { "from": "addressescustomers", "localField": "_id", "foreignField": "고객", "as": "addr" }} ]) – Carlos