programing

Node.js - Mongoose와 관계 만들기

powerit 2023. 6. 7. 23:21
반응형

Node.js - Mongoose와 관계 만들기

나는 2개의 스키마가 있습니다.Custphone그리고.Subdomain.Custphone belongs_to a Subdomain그리고.Subdomain has_many Custphones.

문제는 Mongoose를 사용하여 관계를 만드는 것입니다.제 목표는 custphone.subdomain을 실행하여 custphone이 속한 subdomain을 얻는 것입니다.

내 스키마에는 이런 것이 있습니다.

SubdomainSchema = new Schema
    name : String

CustphoneSchema = new Schema
    phone : String
    subdomain  : [SubdomainSchema]

고객 전화 결과를 인쇄하면 다음과 같이 표시됩니다.

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

그 때.Custphone결과는{"$oid": "4e9b532b01c642bf4a000003"}MongoDB에서.

하고싶다custphone.subdomain그리고 고객 전화의 하위 도메인 개체를 가져옵니다.

Mongoose의 새로운 채우기 기능을 사용해 보려고 하는 것 같습니다.

위의 예를 사용하여:

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

SubdomainSchema = new Schema
    name : String

CustphoneSchema = new Schema
    phone : String
    subdomain  : { type: ObjectId, ref: 'SubdomainSchema' }

subdomain필드가 다음과 같은 '_id'로 업데이트됩니다.

var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()

var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()

실제로 데이터를 가져오려면subdomain조금 더 복잡한 쿼리 구문을 사용해야 하는 필드:

CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) { 
// Your callback code where you can access subdomain directly through custPhone.subdomain.name 
})

비슷한 문제가 있어서 mongoose의 Model.findByIdAndUpdate()를 사용해야 했습니다.

문서: http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

이 게시물은 또한 저에게 도움이 되었습니다: http://blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/comment-page-1/ #http-http12.

언급URL : https://stackoverflow.com/questions/7810892/node-js-creating-relationships-with-mongoose

반응형