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

416
Vistas
getting count within a findOne of a mongoose schema array field

I want to use Mongoose to return information about a user to populate their profile. I've been using findOne to populate a list of their comments along with basic profile information through embedded documents and with .populate. I want to get a count of the friends that they have by counting how many objects are in the friends array.

It looks like aggregate is one of doing that, but how can I use both? or is there a simple way of doing a count in the findOne query?

var UserSchema = new Schema({
  username:  String,
  comments       : [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
  friends: [
					{ 
						id: { type: Schema.Types.ObjectId, ref: 'User' },
						permission: Number 
					}
  ]
})
  
var User = mongoose.model('User', UserSchema);
var Comment = mongoose.model('Comment', CommentSchema);

app.get('/profile/:username', function(req, res) {
User
.findOne({ username: req.params.username }, 'username friends -_id')
	.populate({
		path: 'current',
		model: 'Comment',
		select: 'comment author -_id date',
		populate: {
			path: 'author',
			model: 'User',
			select: 'username firstName lastName -_id'
		}
	})	
.exec(function(err, user) {
//
})
)}

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

0

If user returns with friends array, why don't you return just user.friends.length ?

If you want just count, use this

User.aggregate([
     {
        $match: { username: req.params.username }
     },
     {
        $unwind: "$comments"
     },
     {
        $lookup: {
           from: "Comment",
           localField: "comments",
           foreignField: "_id",
           as: "comments"
        }
     },
     { 
        "$group": {
            "_id": "$_id",
            "friends": { "$first": "$friends"},
            "comments": { "$push": "$comments" }
         }
     },
     {
        $project: {
            _id: 0, 
            count: {$size: '$friends'},
            comments: 1,
            username: 1
        }
     }
]).exec() ...
about 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