[英]toObject is not a function error in mongoose
This is the filesPost controllers file.这是 filesPost 控制器文件。 Here I fetch all the datas from MongoDB as well I push datas there.在这里,我从 MongoDB 中获取所有数据,并将数据推送到那里。 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.该函数在不登录控制台userInfo的情况下运行良好,但是当我尝试将其登录到控制台时,它给出了userInfo.toObject({getters: true})不是函数的错误。 I have tried toJSON() but I got the same error.我试过 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 })),
});
};
In your async function, your code continues even though the call to User.findById(userId)
isn't complete.在您的异步函数中,即使对User.findById(userId)
的调用未完成,您的代码也会继续。 You can use an await
statement to ensure that the function has run before your code continues.您可以使用await
语句来确保函数在您的代码继续运行之前已经运行。
Your code should work if you change const userInfo = User.findById(userId);
如果您更改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有关更多信息,这里是 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.