#Mongoose index hook

6 messages · Page 1 of 1 (latest)

gilded lantern
#

Couldn't find a way how to create such model hook on nestjs.

I see how to create pre/post hooks that attached to schemas, but this one is specifically needs to be attached to model.
Is this somehow possible to do in MongooseModule.forFeatureAsync factory ?

Example from doc: https://mongoosejs.com/docs/guide.html#indexes

// Will cause an error because mongodb has an _id index by default that
// is not sparse
animalSchema.index({ _id: 1 }, { sparse: true });
const Animal = mongoose.model('Animal', animalSchema);

Animal.on('index', error => {
  // "_id index cannot be sparse"
  console.log(error.message);
});
kindred nest
gilded lantern
#

The thing is this hook needs to be added on model, but not schema itself.

Adding this hook on schema has no effect unfortunately.

#

Got it working like this somehow, but it's not firing every time like it should.
(for each index created it should log "index created",)

@Injectable()
export default class MyService {
  constructor(
    @InjectModel(MyModel.name) private model: MyModel,
  ) {

    model.on('index', (error: any) => {
      console.log("index created")
      if (error) {
        console.error('Error creating indexes:', error)
      }
    })

  }
kindred nest
#

You can always inject the connection (mongoose) and get the model by name like you have in your first code block mongoose.model('name', schema).on()

gilded lantern
#

Is it possible to do this somewhere globally maybe in MongooseModule stuff ?