【问题标题】:Mongoose findByIdAndUpdate not updating the documentMongoose findByIdAndUpdate 不更新文档
【发布时间】:2021-10-23 12:18:24
【问题描述】:

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

在服务器日志上,我只能看到 users.findOne 在我运行 API 时记录,猫鼬也不应该同时运行更新。我可以毫无问题地获取/创建/删除用户。

界面

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 - 

【问题讨论】:

    标签: typescript mongodb express mongoose crud


    【解决方案1】:

    更新不起作用,因为您将{ userData } 作为更新参数传递给findOneAndUpdate()。这相当于 { userData: userData } 并且不适合您的架构。要解决它,您只需要稍作改动即可:

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

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2014-02-19
      • 2015-10-04
      • 2021-01-28
      相关资源
      最近更新 更多