I want to count the number of likes and comments both of which are arrays in the schema.The schema looks like this:
const PostSchema = new mongoose.Schema({
text: {
type: String,
required: "Name is required",
},
photo: {
data: Buffer,
contentType: String,
},
likes: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
comments: [
{
text: String,
created: { type: Date, default: Date.now },
postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
likes: Number,
},
],
postedBy: { type: mongoose.Schema.ObjectId, ref: "User" },
created: {
type: Date,
default: Date.now,
},
});
As both likes and comments are arrays I want to count the number of elements inside them and I am doing it like this,I read about the aggregate function but cant figure out how to use it here as I have to iterate through all the post documents and fetch their likes and comments.
const leaderboard = (req, res) => {
Post.find({}, function (err, docs) {
docs.forEach(function (data) {
var userid = data.postedBy;
console.log(userid);
var likes = data.likes.length;
console.log(likes);
var comments = data.comments.length;
console.log(comments);
const date2 = new Date();
const diffTime = Math.abs(date2 - data.created);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log(diffDays);
const updated = User.findByIdAndUpdate(
userid,
{score: likes+comments+diffDays },
function (errr, doc) {
if (errr) {
console.log(err);
} else {
console.log("Updated User : ", doc);
}
}
);
I will really appreciate the help here,Thanks!
you can try project count the number of elements of comments
and likes
Post.aggregate([
{$project: {_id: 1, count: {$commentssize: '$comments'},count: {$sizelikes: '$likes'}}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.