Node.js - Creating Relationships with Mongoose

JavascriptMongodbnode.jsMongoose

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondonaldView Question on Stackoverflow
Solution 1 - JavascriptDanView Answer on Stackoverflow
Solution 2 - JavascriptConnor LeechView Answer on Stackoverflow