I have a usecase where I have to populate data between 2 mongoose schemas whose schemas look like these:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { Document } from 'mongoose'
@Schema({ timestamps: true, collection: 'notifications' })
export class Notifications extends Document {
@Prop({ required: true })
sourceApp: string
@Prop({ required: true })
body: string
@Prop({ required: true })
redirectionUrl: string
@Prop({ required: false })
metaData: Map<string, any>
@Prop({ required: true })
contactId: string
@Prop({ required: true })
isRead: boolean
@Prop({ required: true })
locationId: string
// change to enum
@Prop({ required: true })
type: string
@Prop({ required: true })
resourceIds: string[]
}
const NotificationsSchema = SchemaFactory.createForClass(Notifications)
NotificationsSchema.virtual('resourcesData', {
ref: 'NotificationResources',
localField: 'resourceIds',
foreignField: 'resourceId',
})
export { NotificationsSchema }
// 2nd Schema
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { Document } from 'mongoose'
@Schema({ timestamps: true, collection: 'notification-resources' })
export class NotificationResources extends Document {
@Prop({ required: true })
resourceId: string
@Prop({ required: true })
data: Map<string, any>
}
export const NotificationResourcesSchema = SchemaFactory.createForClass(
NotificationResources,
)
In the Virtual Part below,I am querying on resourceIds like fetch all the items from NotificationResources whose resourceId is in resourceIds array.
NotificationsSchema.virtual('resourcesData', {
ref: 'NotificationResources',
localField: 'resourceIds',
foreignField: 'resourceId',
})
But the localField only works with single field not arrays,How to fix this? whats the workaround?
I am fetching data like this:
async getUnReadNotifications(contactId: string, read: boolean) {
const notificationsFilterQuery: any = {
contactId,
}
if (read !== null) {
notificationsFilterQuery.isRead = read
}
const notifications = await this.notificationsModel
.find(notificationsFilterQuery)
.populate('resourcesData')
.exec()
return notifications
}