0

So, I have a model called Drivers that receive a field called "user", which references a document from another model, like this:


const DriversSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
  },
  {
    timestamps: true,
  }
);
// ...

Querying the collection works as expected, here's an example:

Drivers.find({});
// returns -> 
[
  {
    "name": "John",
    "user": "5e43f8ad2fbb1d0035d5a154",

  }
]

Is there a way to return the actual document represented by the 'user' field?

Thanks!

  • You need aggregate with Mongodb Aggregation framework and use `$lookup` operator to inner join with user collection. With find method it's not possible. Check stackoverflow for examples: $lookup mongoose – Valijon Feb 19 '20 at 21:30
  • Does this answer your question? [How to join multiple collections with $lookup in mongodb](https://stackoverflow.com/questions/35813854/how-to-join-multiple-collections-with-lookup-in-mongodb) – whoami - fakeFaceTrueSoul Feb 19 '20 at 23:01
  • Yes! These solved my problem. It's just... worded differently than I thought. haha Thank you guys! – Misael Vergara Feb 20 '20 at 12:17

0 Answers0