Program Club

Node.js-Mongoose로 관계 만들기

proclub 2020. 12. 11. 18:59
반응형

Node.js-Mongoose로 관계 만들기


2 개의 스키마 CustphoneSubdomain. Custphone belongs_toa SubdomainSubdomain has_many Custphones.

문제는 Mongoose를 사용하여 관계를 만드는 것입니다. 내 목표는 custphone.subdomain을 수행하고 Custphone이 속한 하위 도메인을 가져 오는 것입니다.

내 스키마에 다음이 있습니다.

SubdomainSchema = new Schema
    name : String

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

Custphone 결과를 인쇄하면 다음과 같은 결과가 나타납니다.

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

Custphone결과가 {"$oid": "4e9b532b01c642bf4a000003"}MongoDB에 있을 때 .

내가하고 싶은 custphone.subdomain와 custphone의 하위 도메인 개체를 얻을.


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/#comment-17812

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

반응형