• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

347
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 3 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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda