My Schema contains an array of ObjectIds:
const userSchema = new Schema({
...
article: [{
type: mongoose.Schema.Types.ObjectId,
}],
...
},
https://i.sstatic.net/RcXTF.png
In the example above, I want to count the elements in the array, which should be 10.
I attempted the following method, but it didn't work for me. The req.query.id
represents the _id of the user and is used to filter the specific user with a matching article array.
const userData = User.aggregate(
[
{
$match: {_id: id}
},
{
$project: {article: {$size: '$article'}}
},
]
)
console.log(res.json(userData));
The console.log(article.length)
currently returns 0. How can I achieve this? Is using the aggregate function the correct approach, or is there a better way to count elements in an array?