Home > Mobile >  toObject is not a function error in mongoose
toObject is not a function error in mongoose

Time:06-16

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

CodePudding user response:

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

CodePudding user response:

Just needed to add await.

const userInfo = await User.findById(userId);

  • Related