[英]how to count an array object in a mongdb schema in nodejs?
I want to count the number of likes and comments both of which are arrays in the schema.The schema looks like this:我想计算架构中的赞和评论的数量,这两个都是 arrays。架构如下所示:
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.由于喜欢和评论都是 arrays 我想计算其中的元素数量并且我正在这样做,我读到了聚合 function 但无法弄清楚如何在这里使用它,因为我必须遍历所有发布文件并获取他们的喜欢和评论。
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!我将非常感谢这里的帮助,谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.