SchemaType.prototype.ref()

Parameters
  • ref «String|Model|Function» either a model name, a Model, or a function that returns a model name or model.
Returns:
  • «SchemaType» this

Set the model that this path refers to. This is the option that populate looks at to determine the foreign collection it should query.

Example:

  1. const userSchema = new Schema({ name: String });
  2. const User = mongoose.model('User', userSchema);
  3. const postSchema = new Schema({ user: mongoose.ObjectId });
  4. postSchema.path('user').ref('User'); // Can set ref to a model name
  5. postSchema.path('user').ref(User); // Or a model class
  6. postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name
  7. postSchema.path('user').ref(() => User); // Or a function that returns the model class
  8. // Or you can just declare the `ref` inline in your schema
  9. const postSchema2 = new Schema({
  10. user: { type: mongoose.ObjectId, ref: User }
  11. });