Search code examples
mongodbundefineddeno

I can not read the $iod from Mongodb response in a Deno app


I want to write a simple registration function and this is my code:

  async register(ctx: RouterContext) {
    const  { email, password }  = await ctx.request.body().value;

    let user = await User.findOne({ email });
    if (user) {
      ctx.response.status = 422;
      ctx.response.body = { message: "Email is already exist" };
      return;
    }
    const hashedPassword = hashSync(password);
    user = new User({  email, password: hashedPassword });
    await user.save();
    ctx.response.status = 201;
    console.log("This is the new useeeeeer", ctx.response.body = {
      id: user.id,
      name: user.name,
      email: user.email
    });
  }

And this is the User.ts class:

export default class User extends BaseModel {
  public id: string = "";
  public name: string = "";
  public email: string = "";
  public password: string = "";

  constructor({ id = "", name = "", email = "", password = "" }) {
    super();
    this.id = id;
    this.name = name;
    this.email = email;
    this.password = password;
  }

  static async findOne(params: object): Promise<User | null> {
    const user = await userCollection.findOne(params);
    if (!user) {
      return null;
    }
    return new User(User.prepare(user));
  }

  async save() {
    const { $oid } = await userCollection.insertOne(this);
    console.log('this is oid ', $oid);
    //delete this.id;
    this.id = $oid;
    console.log("This is the new UUser", this);

    return this;
  }
}

The problem is that it doesn't work properly and I see { id: undefined, ...} in responses do I get. How can I get the id that MongoDB creates for my user and replace and save it with the User.id?


Solution

  • It seems there is no $oid in new version of MongoDB and we must use _id instead. Although I am not sure about it but could solve my problem.