Home > Back-end >  Can't find and update record from MongoDB(nest js)
Can't find and update record from MongoDB(nest js)

Time:10-19

userId in database:

 userId:"610405b8f3e5fb0484f5fac2"

I want to update tha data by that Id,but getting 500Internal Server Error.I am trying in this way:

service.ts

  public async updateUser(
    UserId: any,
    data: any
): Promise<any | Error> {
    try {
        return new Promise((resolve, reject) => {
            UserCollection.findByIdAndUpdate(
                UserId,
                { ...data },
                (err: any, success: any) => {
                    if (err) {
                        reject(err);
                    }
                    if (!success) {
                        resolve(false);
                    } else {
                        resolve(success);
                    }
                }
            );
        });
    } catch (e) {
        console.log('service error\n', e);
        throw e;
    }
}

controller.ts

  public updateUserController = async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => {
    try {
        if (req.body.UserId!='') {
            let results = await this.ServicesService.updateUser(req.params.UserId, req.body);
            if (results != false) {
                this.success(res, 'Updated Successfully', 200, results._id);
            }
        } 
        return await this.error(res, 'Something Went Wrong!.', 500);
    } catch (e) {
        next(e)
    }
}

How to achive this,thanks....

CodePudding user response:

I realized my mistake,Instead of using findByIdAndUpdate,I used findOneAndUpdate,error solved.

UserCollection.findOneAndUpdate(
            UserId,
            { ...data },
            (err: any, success: any) => {
                if (err) {
                    reject(err);
                }
                if (!success) {
                    resolve(false);
                } else {
                    resolve(success);
                }
            }
        );

CodePudding user response:

you can simple have the updateMany() method to update multiple documents with same userId at once.

  • Related