I have the following aggregation query in my code which matches a user based on their _id
and then sets their privacy status to a value, and filters the notifications
array based the type
attribute of a notification. It should then update the document using $merge
User.aggregate([
{
$match: { _id: new mongoose.Types.ObjectId(req.user._id) },
},
{
$lookup: {
from: "Notification",
localField: "notifications",
foreignField: "_id",
as: "notifications",
},
},
{
$set: {
privacyStatus: value,
notifications: {
$filter: {
input: "$notifications",
cond: {
$ne: ["$$this.type", "follow_request"],
},
},
},
},
},
{
$project: {
username: 1,
notifications: 1
},
},
{
$merge: {
into: "users",
},
},
]).then((result) => {
console.log(result)
res.send("Done")
})
Here is my User model:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
minLength: 4,
maxLength: 30,
},
privacyStatus: {
type: Boolean,
required: true,
default: false,
},
notifications: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Notification",
},
],
})
After running this query, the document is successfully updated in the database so I know the $match
is working correctly, however I get an empty array when logging the result. I am using $project
to try return the notifications as well as the username.
How can I return the original user document after the aggregation has been complete?