【发布时间】:2021-07-25 12:27:40
【问题描述】:
我有两个收藏:
用户
var UserSchema = new mongoose.Schema({
likes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Products' }],
dislikes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Products' }],
})
产品
var ProductSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
})
我想退回所有不在 User.likes 或 User.dislikes 中的产品。以下是我目前的做法:
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 } },
}
])
它有效,但如果可能,我想切换到使用聚合管道框架来执行此操作。比较两个系列似乎并不容易......我已经尝试了一段时间但没有运气。 $setUnion 和 $setDifference 看起来很有希望,但我找不到一种方法来设置用户好恶的联合,然后是所有产品的差异。
【问题讨论】:
标签: mongodb mongoose nosql aggregation-framework nosql-aggregation