Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

339
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

Just needed to add await.

const userInfo = await User.findById(userId);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda