node.js - {select: false} 在 mongoose 查询上的工作方式不同
问题描述
我正在尝试在 mongoose 中创建一个用户,并在 User.create 查询后返回它,而无需密码字段。我在模型模式中的密码字段上设置了“select:false”,但它在 User.create 之后不断返回密码作为响应。
// models/user.js
const userSchema = new mongoose.Schema({
// ...
password: {
type: String,
required: true,
minlength: 5,
select: false,
},
});
// routes/index.js
routes.post(
"/sign-up",
celebrate({
body: Joi.object().keys({
name: Joi.string().min(2).max(30),
about: Joi.string().min(2).max(30),
avatar: Joi.string().pattern(RegExp(urlChecker)),
email: Joi.string().required().email(),
password: Joi.string().required().min(5),
}),
}),
usersController.createUser,
);
// controllers/user.js
const User = require("../models/user");
exports.createUser = (req, res, next) => {
const {
name,
about,
avatar,
email,
password,
} = req.body;
bcrypt
.hash(password, 10)
.then((hash) => User.create({
name,
about,
avatar,
email,
password: hash,
}))
.then((user) => {
if (!user) {
throw new InvalidInputError("Invalid data");
}
res.send(user); // response includes password field
})
.catch((err) => next(err));
};
但是,如果我在 User.create 之后添加 User.findById 查询,我会收到没有密码字段的响应。
// controllers/user.js
// ...
.then((user) => {
if (!user) {
throw new InvalidInputError("Invalid data");
}
return User.findById(user._id);
})
.then((user) => {
if (!user) {
throw new NotFoundError("User not found");
}
res.send(user); // works fine!
})
{select: false} 仅适用于猫鼬中的查找查询,我说得对吗?在 User.create 方法之后不返回密码字段是否还有其他解决方法?
解决方案
保存的结果是一个对象模型,您应该将其转换为对象并删除密码键,如下所示:
user = user.toObject()
delete user.password
res.send(user); // response includes password field
推荐阅读
- flutter - Flutter CheckboxListTile 无法在测试中检查标题:TextFormField
- ios - 如何使用 ARKit 点击将 SCNNode 添加到场景视图?
- amazon-web-services - AWS QuickSight:计算表中的聚合百分比
- express - Express 中的异步路由功能和异步中间件是否阻塞了执行过程(2021 年)?
- kotlin-multiplatform - Kotlin 多平台项目依赖于另一个带有 cocoapods 的项目
- javascript - 如何添加一个函数,以便用户可以输入“p”或“a”来获取矩形的周长或面积?
- python-3.x - 在python中减去日期时间类型的问题
- html - 获取文本输入字段的值并将这些值发送到 RabbitMQ 服务器
- windows - 运行 npm 命令后文件位置不会返回
- azure-devops - 如何通过 CLI 构建 azure 管道