猫鼬 findByIdAndUpdate 不更新文档

Mongoose findByIdAndUpdate not updating the document

一直在尝试使用 Mongoose findByIdAndUpdate 按 ID 更新文档,操作 运行s 没有错误,但更改未反映在数据库中。

在服务器日志上我只能看到 users.findOne 在我 运行 和 API 时记录,不应该 mongoose 运行 也随之更新。我可以 get/create/delete 用户没有任何问题。

界面

export interface User {
  _id: string;
  email: string;
  password: string;
}

型号

const userSchema: Schema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
});

控制器

public updateUser = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const userId: string = req.params.id;
      const userData: CreateUserDto = req.body;
      const updateUserData: User = await this.userService.updateUser(userId, userData);

      res.status(200).json({ data: updateUserData, message: 'updated' });
    } catch (error) {
      next(error);
    }
  };

服务

  public async updateUser(userId: string, userData: CreateUserDto): Promise<User> {
    if (isEmpty(userData)) throw new HttpException(400, "You're not userData");

    if (userData.email) {
      const findUser: User = await this.users.findOne({ email: userData.email });
      if (findUser && findUser._id != userId) throw new HttpException(409, `You're email ${userData.email} already exists`);
    }

    if (userData.password) {
      const hashedPassword = await bcrypt.hash(userData.password, 10);
      userData = { ...userData, password: hashedPassword };
    }

    const updateUserById: User = await this.users.findOneAndUpdate({ _id: userId }, { userData }, { new: true });
    if (!updateUserById) throw new HttpException(409, "You're not user");

    return updateUserById;
  }

dtos

import { IsEmail, IsString } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  public email: string;

  @IsString()
  public password: string;
}

当我 运行 更新时记录 API

mongodbexpress | {"t":{"$date":"2021-08-23T05:19:26.698+00:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1629695966:698802][1:0x7f5f10065700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 664, snapshot max: 664 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 2092"}}
server    | Mongoose: users.findOne({ email: 'newemil@gmail.com' }, { projection: {} })
server    | Mongoose: users.findOne({ _id: ObjectId("6122ae51d922ae0a85b85484") }, { new: true, projection: {} })
server    | 2021-08-23 05:19:27 info: PUT /users/6122ae51d922ae0a85b85484 200 75.025 ms - 

更新无效,因为您将 { userData } 作为更新参数传递给 findOneAndUpdate()。这相当于 { userData: userData } 并且不适合您的模式。要解决它,你只需要做一点改变:

const updateUserById: User = await this.users.findOneAndUpdate({ _id: userId }, userData, { new: true });