Issue:
Encountering problem with aggregation in a non-existent field.I am working with the Follow Schema
which has the following fields:
_user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
following: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
default: []
}],
followers: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
default: []
}],
When a user follows someone, the code looks like this:
const bulk = Follow.collection.initializeUnorderedBulkOp();
bulk.find({ _user_id: req.user._id }).upsert().updateOne({
$addToSet: {
following: Types.ObjectId(follow_id)
}
});
bulk.find({ _user_id: Types.ObjectId(follow_id) }).upsert().updateOne({
$addToSet: {
followers: req.user._id
}
});
bulk.execute((err, doc) => {
...
})
However, when new data is being saved for the first time, the bulk
operation saves only the specified $addToSet
field.
For instance, if I run this:
bulk.find({ _user_id: Types.ObjectId(follow_id) }).upsert().updateOne({
$addToSet: {
followers: req.user._id
}
});
It will result in:
{
_id: ObjectId(544987dfgsld3),
followers: [ ObjectId(34578778g6d8f7g6) ] // Followers get saved
// How can I initialize the following as an empty array?
}
This leads to errors in aggregation because the field does not exist.
const result = await Follow.aggregate([
{
$match: { _user_id: user._id }
},
{
$project: {
_id: 0,
followingCount: { $size: '$following' }, // Error occurs here - size field must be an array but it doesn't exist
followersCount: { $size: '$followers' },
followers: 1
}
},
]);