【发布时间】:2021-06-06 21:08:51
【问题描述】:
我阅读了documentation,其中描述了如何通过提取 id 找到的对象的某些字段来解决问题。我尝试编写类似的代码,但分配给 user 变量的输出包括单个元素的所有字段。
export const getUser = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { id } = req.params;
const userFetchesOwnData = req.app.locals.userId === id;
let user: any;
if (req.app.locals.isAuth && userFetchesOwnData) {
user = await User.findById(
id,
"email username age sex location summary"
).exec();
} else {
user = await User.findById(
id,
" username age sex location summary"
).exec();
}
console.log(user);
res.status(200).json({
message: "User fetched",
user,
});
} catch (err) {
if (!err.statusCode) {
err.statusCode = 500;
}
next(err);
}
};
【问题讨论】:
-
查询看起来很正确。用户变量应该具有所有选定的字段 + _id 字段。如果需要排除 _id 字段则需要添加
-_id。
标签: javascript node.js mongodb typescript mongoose