Why .populate returns [model] and not the content of the collection

Viewed 20

I'm learning mongoose, and I have the below code where I create an Author and a Course and I reference the Author in a Course model.

const Course = mongoose.model(
  "Course",
  new mongoose.Schema({
    name: String,
    author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Author",
    },
  })
);

const Author = mongoose.model(
  "Author",
  new mongoose.Schema({
    name: String,
    bio: String,
    website: String,
  })
);

Then I try to list all the courses and populate the author prop but I just get author: [model] instead of the contents.

async function listCourses() {
  /* Use the populate method to get the whole author,
  and not just the id.
  The first arg is the path to the given prop
  i.e. author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Author",
    },
    We can populate multiple props ...
  */
  const courses = await Course.find()
    .populate('author')
    // .populate({ path: "author", model: Author })
    // .populate("author", "name -_id")
    // .populate('category')
    .select("name author");
  console.log(courses);
}

I tried several ways to get the content. I also tried some solutions from this question, but nothing worked.

This is the log I get:

_doc: {
      _id: 632c00981186461909cebb20,
      name: 'Node Course',
      author: [model]
    },

I checked the docs to see if the way I'm trying is deprecated, but they have the same code as here.

So how can I see the content?

Thanks!

1 Answers

After all, it was a "wrong" logging approach. By iterating over the array of courses and accessing the author prop, the content was revealed.

This is the modified log, in the listCourses function;

console.log(courses.map((c) => c._doc.author));

And this is the output:

 isNew: false,
    errors: undefined,
    _doc: {
      _id: 632bfd0c7f727d15fcd3f712,
      name: 'Mosh',
      bio: 'My bio',
      website: 'My Website',
      __v: 0
    },

Related