Node.js - Creating Relationships with Mongoose

前端 未结 2 754
予麋鹿
予麋鹿 2020-12-07 11:32

I have 2 Schemas, Custphone and Subdomain. Custphone belongs_to a Subdomain and Subdomain

相关标签:
2条回答
  • 2020-12-07 11:59

    I had a similar problem and had to use mongoose's Model.findByIdAndUpdate()

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

    this post helped me also: http://blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/comment-page-1/#comment-17812

    0 讨论(0)
  • 2020-12-07 12:00

    It sounds like you're looking to try the new populate functionality in Mongoose.

    Using your example above:

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

    The subdomain field will be is updated with an '_id' such as:

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

    To actually get data from the subdomain field you're going to have to use the slightly more complex query syntax:

    CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) { 
    // Your callback code where you can access subdomain directly through custPhone.subdomain.name 
    })
    
    0 讨论(0)
提交回复
热议问题