[英]toObject is not a function error while converting mongoose object
[英]toObject is not a function error in mongoose
这是 filesPost 控制器文件。 在这里,我从 MongoDB 中获取所有数据,并将数据推送到那里。 该函数在不登录控制台userInfo的情况下运行良好,但是当我尝试将其登录到控制台时,它给出了userInfo.toObject({getters: true})不是函数的错误。 我试过 toJSON() 但我得到了同样的错误。
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 })),
});
};
在您的异步函数中,即使对User.findById(userId)
的调用未完成,您的代码也会继续。 您可以使用await
语句来确保函数在您的代码继续运行之前已经运行。
如果您更改const userInfo = User.findById(userId);
您的代码应该可以工作至
const userInfo = await User.findById(userId);
有关更多信息,这里是 async/await 文档: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
只需要添加等待。
const userInfo = await User.findById(userId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.