Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - Node.js - Creating Relationships with Mongoose

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

The problem is in creating the relationship using Mongoose. My goal is to do: custphone.subdomain and get the Subdomain that the Custphone belongs to.

I have this in my schemas:

SubdomainSchema = new Schema
    name : String

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

When I print the Custphone result I get this:

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

When the Custphone result has {"$oid": "4e9b532b01c642bf4a000003"} in MongoDB.

I want to do custphone.subdomain and get the subdomain object of the custphone.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...