skip to Main Content

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 })),
  });
};

2

Answers


  1. Just needed to add await.

    const userInfo = await User.findById(userId);

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search