복붙노트

[MONGODB] Node.js를이 - 몽구스와의 관계 만들기

MONGODB

Node.js를이 - 몽구스와의 관계 만들기

나는 2 스키마, Custphone 및 하위 도메인 있습니다. Custphone belongs_to 하위 도메인 및 하위 도메인 has_many Custphones.

문제는 몽구스를 사용하여 관계를 만드는 것이다. custphone.subdomain을하고 Custphone가 속한 하위 도메인을 얻을 : 내 목표는하는 것입니다.

내 스키마이있다 :

SubdomainSchema = new Schema
    name : String

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

나는 Custphone를 인쇄 할 때 나는이 얻을 결과 :

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

MongoDB의에서 다음 Custphone 결과는 { "4e9b532b01c642bf4a000003" "$ OID를"}가있는 경우.

나는 custphone.subdomain 할과 custphone의 하위 도메인 개체를 얻을합니다.

해결법

  1. ==============================

    1.그것은 당신이 몽구스의 새로운 채우기 기능을 시험해보고있는 것처럼 들린다.

    그것은 당신이 몽구스의 새로운 채우기 기능을 시험해보고있는 것처럼 들린다.

    귀하의 예를 들어 위의 사용 :

    var Schema = mongoose.Schema,
        ObjectId = Schema.ObjectId;
    
    SubdomainSchema = new Schema
        name : String
    
    CustphoneSchema = new Schema
        phone : String
        subdomain  : { type: ObjectId, ref: 'SubdomainSchema' }
    

    하위 도메인 필드와 같은 '_id'로 업데이트됩니다

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

    실제로는 약간 더 복잡한 쿼리 구문을 사용해야 할거야 하위 도메인 필드에서 데이터를 얻으려면 :

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

    2.나는 비슷한 문제를 가지고 있었고, 몽구스의 Model.findByIdAndUpdate를 사용했다 ()

    나는 비슷한 문제를 가지고 있었고, 몽구스의 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

  3. from https://stackoverflow.com/questions/7810892/node-js-creating-relationships-with-mongoose by cc-by-sa and MIT license