What is the function of the populate method in Mongoose?

Asked

Viewed 1,654 times

0

I am doubtful to understand the functionality of the populate method in Mongoose

  • Man, what’s the question? You gotta have a crystal ball to know what your question is.

1 answer

2


It is an alternative for the operator $lookup

Picture the scenario:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const pessoaSchema = Schema({
  _id: Schema.Types.ObjectId,
  nome: String,
  idade: Number,
  historias: [{ type: Schema.Types.ObjectId, ref: 'Historia' }]
});

const historiaSchema = Schema({
  autor: { type: Schema.Types.ObjectId, ref: 'Pessoa' },
  titulo: String,
  fas: [{ type: Schema.Types.ObjectId, ref: 'Pessoa' }]
});

const Historia = mongoose.model('Historia', historiaSchema);
const Pessoa = mongoose.model('Pessoa', pessoaSchema);

If you want to do a search on Historia taking the data of the respective author (i.e., a JOIN in SQL), you can use the function populate to fill the property autor with the data of the author concerned instead of showing only his identifier:

Historia.
  findOne({ titulo: 'Exemplo' }).
  populate('autor')

Documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.