Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Mongo model self reference

Tags:

mongoose

People also ask

Can a Mongoose model reference itself?

Yes it worked exactly as it should! I was just thinking about it in class and had nowhere to test it; truthfully, a question here was probably unnecessary, I just didn't want to lose the thought without an answer!

What is a Mongo model?

Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What are references in mongoose?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.


I'm using Mongoose. This works for me, I'm simply using this as a reference to the model. I have a Comment model. Comments can have a reply that is also Comment.

var Comment = new mongoose.Schema({
  id: { type: ObjectId, required: true },
  comment:    { type: String },
  replies:    [ this ],
});    

I know this question is old. But I stumbled upon this as I was looking for a solution to a similar problem. So, this is for future knowledge seekers!

Ankur's answer will help if you want the referals created inside the user document. Ex:

{
  _id: 'XXX',
  ...
  referals: [{_id:'yyy',email: ''}]
}

I think Using Mongoose Virtuals will help scale the application better. With virtuals, you wouldn't have to create duplicate records.

So if you decide to use Mongoose Virtuals, your schema would look like this

var userSchema = new mongoose.Schema({
  _id: { type: Schema.ObjectId },
  email: { type: String, unique: true },
  ipAddress: { type: String },
  referedBy: {
    type: mongoose.Schema.Types.ObjectId, ref: 'User'
  },
  redeem_token: {type: String, unique: true}
});

userSchema.virtuals('refereals',{
   ref: 'User',
   localField: '_id',
   foreignField: 'referedBy',

   justOne: false,
},{ toJSON: { virtuals: true } }); /* toJSON option is set because virtual fields are not included in toJSON output by default. So, if you don't set this option, and call User.find().populate('refereals'), you won't get anything in refereals */

var User = mongoose.model('User', userSchema);

Hope this helps. If I am wrong, please correct me as I am new to this.