首页 > 解决方案 > {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 方法之后不返回密码字段是否还有其他解决方法?

标签: node.jsmongodbmongoose

解决方案


保存的结果是一个对象模型,您应该将其转换为对象并删除密码键,如下所示:

user = user.toObject()
delete user.password
res.send(user); // response includes password field 

推荐阅读