Alberto
Alberto

Reputation: 399

Mongoose get only the length of a field

This is an example of my Mongoose schema:

mongoose.model('Support', {
  createdBy: mongoose.Schema.Types.ObjectId,
  title: String,
  replies: { type: Array, default: [] }
}

The replies array can contain several objects, to which I'm not interested in the first query, but I do need the length of the array.

Is there a mongoose solution for this problem? Currently I'm just looping through each document.

My code so far:

Support.find({}, function(err, docs) {
  if (err) throw err;

  async.each(docs, function(doc, next) {
    doc.replies = doc.replies.length;
    next();
  }, function() {
    /* Work with the result */
  }
});

Upvotes: 3

Views: 2254

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can use the $size operator with aggregate to get the number of items in an array:

Support.aggregate(
    {$project: {
        createdBy: 1,
        title: 1,
        replies: {$size: '$replies'}
    }},
    function(err, docs) { ... }
);

Upvotes: 3

Related Questions