SakoBu SakoBu - 6 days ago 4
Node.js Question

Schema Association in Mongoose

I have 2 models:

Here is the User Model:

const userSchema = new mongoose.Schema({
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
passwordResetToken: String,
passwordResetExpires: Date,

facebook: String,
twitter: String,
tokens: Array,

profile: {
name: String,
gender: String,
location: String,
website: String,
picture: String
}
}, { timestamps: true });


And here is the Revive Model:

const reviveSchema = new mongoose.Schema({
reviveShowName: {type: String, required: true},
reviveTitle: {type: String, required: true},
reviveCategory: {type: String, required: true},
reviveGoal: {type: Number, required: true},
revivePhoto: {type: String, required: true},
reviveVideo: {type: String},
reviveStory: {type: String},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
name: String
}
}, { timestamps: true });


In the Revive model, I'm trying to the reference the author and get the author's id and that works... How do I also get the name from profiles -> name...? Clearly
name: String
is wrong...

Answer

Mongoose relations work, based on the ref and type value of the nested object. In your case you have associated the id property of author to point to the User model.

If you want to populate the author with the user information, you should just do :

author: {     
  type: mongoose.Schema.Types.ObjectId,
  ref: "User"
}

Then in your query you just use populate

Revive.find({})
      .populate( 'author' )
      .exec( function( error, docs ) {
          console.log( docs ); // will have `[{author:{profile:{...}}}]` data
      } );