I am currently facing a problem where I want to retrieve listings from MongoDB using mongoose which a user has not previously liked.
Listings table:
const listingSchema = new Schema({
_id,
...etc
})
listingSchema.virtual('listingLikes',{
ref:'ListingLikes',
...etc
})
Listing likes table:
const listingLikesSchema = new Schema({
_id,
listingId,
userId
})
What I want to be able to is perform a query such as this one:
ListingModel.find().populate('listingLikes').where({'listingLikes.userId':{$ne:userId}}).limit(10).exec()
Basically obtaining all listings where the user has not liked. The following query works to achieve this:
Listing.find().where({_id:{$nin:[ ...All previously liked user listings in the listing likes model ) ]}})
However this is I believe is largely inefficient (have to load all users previously liked listings into memory before finding the listings).
How can I do this in a more efficient manner? ideally without modifying the current Schema.