Home > database >  mongoose not pushing value into array of mongodb
mongoose not pushing value into array of mongodb

Time:12-16

I am trying to add friends to my user in MongoDB, the friend and the user values are both present, but it won't add them to the database. I have tried the following 2 options I could think of:

  async addFriend(email: string, friendId: string): Promise<User> {
    const friend = await this.userModel.findOne({ _id: friendId });
    return this.userModel.findOneAndUpdate(
       { email: email },
       { $push: { friends: { ...friend } } }
    );
  }

the second option gives the error: Cannot read properties of undefined (reading 'push')

  async addFriend(email: string, friendId: string): Promise<User> {
    const friend = await this.userModel.findOne({ _id: friendId });
    const user = await this.userModel.findOne({ email: email });
    user.friends.push(friend);
    await user.save();
    return user.toObject({ versionKey: false });
  }

my user schema:

export const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  birthDay: {
    type: Date,
    required: true,
  },
  games: [GameSchema],
  reviews: [ReviewSchema],
  friends: [FriendSchema],
});

the friend schema

export const FriendSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  birthday: {
    type: Date,
    required: true,
  },
});

the controller that receives the API request

@Controller('user')
export class UserController {
  constructor(private userDB: UserRepository) {}

  @Put()
  async addFriend(
    @Headers('authorization') authJwtToken,
    @Body('friendId') friendId: string,
  ): Promise<User> {
    console.log(friendId);
    const user = jwt.verify(authJwtToken, JWT_SECRET);
    console.log(user.email);
    return this.userDB.addFriend(user.email, friendId);
  }
}

this is the object I am trying to insert to the friends array

{
  roles: [],
  _id: new ObjectId("638b5b66b3273651992687dd"),
  name: 'John Doe',
  email: '[email protected]',
  password: 'pbkdf2$10000$f9a071fd2dcbe7c620af19b8dfe4484caa9a616bf8320739a704eec92adb740573b4efd6b7f39464264b30d872424cd6cb6714e06fa254840157a2014fb3b747$07cfcf77b55218416c3187c5d4c98b9fd6d823d08fc4132f24c46a1f8dcdc6c07a7bde480f6f0b898e72d27141e7a548f7460e461103d97d1cfa2dbfe4545135',
  birthday: '2005-12-18'
}

CodePudding user response:

swapping my usersmodule an authmodule imports in app.module.ts around seems to have fixed the error, i'm not sure why this was the cause of my issues but it works now

@Module({
//before: authmodule, then usersmodule
  imports: [GamesModule, UsersModule, AuthModule, MongooseModule.forRoot(MONGO_CONNECTION)],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(GetUserMiddleware).forRoutes(GamesController, UsersController);
  }
}
  • Related