Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - get length of array in model

I have this Mongoose schema:

var postSchema = mongoose.Schema({

    postId: {
        type: Number,
        unique: true
    },

    upvotes: [
        {
            type: Number,
            unique: true
        }
    ]

});

what the best query to use to get the length of the upvotes array? I don't believe I need to use aggregation because I only want to query for one model, just need the length of the upvotes array for a given model.

Really struggling to find this info online - everything I search for mentions the aggregation methodology which I don't believe I need.

Also, as a side note, the unique schema property of the upvotes array doesn't work, perhaps I am doing that wrong.

like image 449
Alexander Mills Avatar asked Oct 31 '15 03:10

Alexander Mills


2 Answers

postSchema.virtual('upvoteCount').get(function () {
    return this.upvotes.length
});

let doc = await Post.findById('foobar123')

doc.upvoteCount // length of upvotes

like image 56
ram Avatar answered Sep 18 '22 16:09

ram


I'm not normally a fan of caching values, but it might be an option (and after finding this stackoverflow answer is what I'm going to do for my use case) to calculate the length of the field when the record is updated in the pre('validate') hook. For example:

var schema = new mongoose.Schema({
    name: String,
    upvoteCount: Number,
    upvotes: [{}]
});

schema.pre('validate', function (next) {
  this.upvoteCount = this.upvotes.length
  next();
});

Just note that you need to do your updates the mongoose way by loading the object using find and then saving changes using object.save() - don't use findOneAndUpdate

like image 33
Ryan Knell Avatar answered Sep 18 '22 16:09

Ryan Knell