I have two collections:
User
var UserSchema = new mongoose.Schema({ likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Products' }], dislikes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Products' }], })
Product
var ProductSchema = new mongoose.Schema({ title: { type: String, required: true, }, })
I would like to return all of the products that is not in the User.likes or User.dislikes. Here is how I am currently doing it:
const user = await User.findById(req.user.id, 'likes dislikes'); let seenProducts = []; user.likes.forEach(p => { seenProducts.push(new mongoose.Types.ObjectId(p)); }) user.dislikes.forEach(p=> { seenProducts.push(new mongoose.Types.ObjectId(p)); }) Product.aggregate([ { $match: { _id: { $nin: seenProducts } }, } ])
It works, but I would like to switch over to using the aggregration pipeline framework to do this if possible. It does not seem like it is easy to compare two collections... I have been trying this for a while with no luck. $setUnion
and $setDifference
look promising, but I can't find a way to set the union of the likes & dislikes of the user, and then the difference of that with all products.
没有评论:
发表评论