Home > Software engineering >  findById returns all fields except one that references another document
findById returns all fields except one that references another document

Time:05-16

When I use findById on my model, it returns all fields except the one that references another document.

This is the document on the database (MongoDB Document):

{
  _id: ObjectId("62791a34bfdd286f0d9105b7"),
  title: 'yes!',
  path: 'public/uploads/birds-1.mp4',
  author: {
    _id: ObjectId("6276b73f1793107c9027a8ee"),
    name: -,
    email: -,
    image: -,
    emailVerified: null,
  },
}

And this is what I'm getting when using findById (doesn't return the author field):

{
  _id: new ObjectId("62791a34bfdd286f0d9105b7"),
  title: 'yes!',
  path: 'public/uploads/birds-1.mp4'
}

Videos Schema:

mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  path: {
    type: String,
    required: true,
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
})

CodePudding user response:

You should explicitly populate the referenced field when running your query:

const video = await Videos.findById(_id).populate('author').exec()

You can read more about query population on the official docs.

CodePudding user response:

According to the MongoDB documentation you'll need to perform a lookup on the referenced table.

The references ID page notes that what you are doing is correct. You are setting the _id of an object as a reference point on another object within your schema.

However it makes the important distinction in at the top that you need to use the $lookup functionality to get a record and it's referenced records in one pull.

This is corroborated by a similar, previously answered question here on Stack Overflow.

Mongoose supports the $lookup functionality through a function they call "populate" which I what I assume you'll want to perform the lookup in since your question is tagged that you're using Mongoose.

If you want help implementing the populate functionality paste in your code you are using to retrieve data from your database and someone will likely help you.

  • Related