假設我有一個帖子模型,模式包含UserId、Title、Desc和likes陣列,其中以userId作為參考
。當我進行查詢時,我得到一個虛擬屬性,像這樣找出一個帖子的喜歡數
。schema.virtual("numLikes") 。 get(function () {
return this.likes.length;
});
但問題是,當我運行findById()方法時,我不想從資料庫中獲取喜歡,因為喜歡陣列會包含大量的用戶串列
。 const post = await Post. findById(postId).select("-likes -shares") 。
那么,我如何在不獲取喜歡陣列的情況下獲得喜歡數呢?
uj5u.com熱心網友回復:
我相信這可以通過聚合來完成,通過在一個投影中使用$size運算子:
const aggregate = Post.aggregate( [
{ $match: {_id: postId}}。
{ $project: {
numberOfLikes: { $size: "$likes" }
}
}
]);
https://docs.mongodb.com/manual/reference/operator/aggregation/size/ https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-project
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/319842.html
標籤:
上一篇:Mongoose自動改變值的型別
