我正在查询用户集合,并且不想发回密码。我的主要观点是,是否可以对mongodb对象执行javascript操作。这是我的代码:
router.get("/:userId", async (req, res) => {
try {
const user = await User.findById(req.params.userId);
delete user.password;
if (user.parent !== undefined) {
const referrer = await User.findOne({ _id: user.parent });
return res.json({ user, referrer });
}
res.json(user);
} catch (error) {
res.status(400).json(error);
}
});
我得到了这个输出
{
"is_deleted": false,
"packages": [],
"_id": "5ed102f3fefa080404db01df",
"name": "parent",
"email": "parent@parent.com",
"gender": "m",
"password": "$2b$10$HTGaoy.AVmoG/A0c/vkikO0NnEBte7f2tvwt2FQE94bZlNiYTeX8i",
"__v": 0
}
我试图对mongodb对象列表执行过滤,但也失败了。
答案 0 :(得分:1)
您可以解构查询返回的对象
const {password, ...restProps } = await User.findById(req.params.userId);
const user = {...restProps};
您还可以配置User
模型,以便在查询结果中默认排除password
字段。
const UserSchema = new mongoose.Schema({
...
password: {
...
select: false
}
});
如果您不想默认排除某个字段,则可以调用select
函数并指定您不想包含在查询结果中的属性。
const user = await User.findById(req.params.userId).select('-password');
有关此的更多信息,请参见SchemaType.prototype.select()
答案 1 :(得分:1)
我将findeOne
与最后的投影一起使用:
const user = await User.findOne({ _id: req.params.userId },{ password: 0 });
通过将值设置为0