[英]get array length in mongoose without aggregate
我有这个 model:
const postSchema = Schema(
{
author: {
type: Schema.Types.ObjectId,
ref: "User",
},
likes: [{
type: Schema.Types.ObjectId,
ref: "Like",
},],
{
timestamps: true,
}
);
我想在不使用聚合的情况下获得点赞数(点赞数组的长度):这可能吗?
exports.getAllPosts = async (req, res) => {
const allPosts = await Post.find()
.populate({ path: "author", select: "firstName lastName email" })
.populate({ path: "likes" })
.then((posts) => {
return res.status(200).json({ Posts_count: postsCount , posts});
})
.catch((err) => {
return res.status(404).json(err);
});
};
不,但是您可以维护自己的计数并在添加或删除 Like 中的项目时更新它。 您可以使用 schema.pre 中间件,更多请参见https://mongoosejs.com/docs/middleware.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.