Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

335
Views
toObject is not a function error in mongoose

This is the filesPost controllers file. Here I fetch all the datas from MongoDB as well I push datas there. The function works very well without logging in console the userInfo but when I try to log it in console, it gives the error that userInfo.toObject({getters: true}) is not a function. I have tried toJSON() but I got the same error.

const { validationResult } = require("express-validator");

const HttpError = require("../models/http-error");
const File = require("../models/file");
const User = require("../models/user");

const getFilesByUserId = async (req, res, next) => {
  const userId = req.params.uid;

  let filePosts;
  try {
    filePosts = await File.find({ creator: userId });
  } catch (err) {
    return next(new HttpError("Fetching failed, please try again.", 500));
  }

  const userInfo = User.findById(userId);

  if (!filePosts || filePosts.length === 0) {
    return next(
      new HttpError("Could not find files for the provided user id.", 404)
    );
  }

  console.log(userInfo.toObject({ getters: true }));
  res.json({
    filePosts: filePosts.map((file) => file.toObject({ getters: true })),
  });
};
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In your async function, your code continues even though the call to User.findById(userId) isn't complete. You can use an await statement to ensure that the function has run before your code continues.

Your code should work if you change const userInfo = User.findById(userId); to

const userInfo = await User.findById(userId);

For more information, here is the async/await documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

about 4 years ago · Juan Pablo Isaza Report

0

Just needed to add await.

const userInfo = await User.findById(userId);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!