#mongodb #mongoose #aggregation-framework #mern #mongoose-populate
Вопрос:
У меня есть такая схема:
const UserSchema = new Schema({
following: [
{
type: Schema.Types.ObjectId,
ref: "users",
},
],
video: {
type: Schema.Types.ObjectId,
ref: "videos",
},
});
module.exports = User = mongoose.model("users", UserSchema);
Я хотел бы получить: User.following, ГДЕ СУЩЕСТВУЕТ следующее.видео
Другими словами, я хотел бы получить список пользователей, за которыми следует конкретный пользователь, у которого есть видео.
Это то, что я делал до сих пор:
const user = await User.aggregate([
{ $match: { _id: ObjectId(user_id) } },
{
$lookup: {
from: "users",
let: { following: "$following" },
pipeline: [{ $match: { $expr: { $in: ["$_id", "$following"] } } }],
as: "following",
},
},
]);
const followed_users = user[0].following;
Но я не смог найти способ отфильтровать отслеживаемых пользователей на основе video
поля.
Есть идеи, как я могу этого добиться?
Ответ №1:
На самом деле, все, что мне нужно было сделать, это:
{
$match: {
video: { $exists: true },
$expr: { $in: ["$_id", "$following"] },
},
},