Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

359
Vistas
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:

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!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

you can try project count the number of elements of comments and likes

Post.aggregate([
    {$project: {_id: 1, count: {$commentssize: '$comments'},count: {$sizelikes: '$likes'}}
])
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda