Search code examples
node.jsapiexpressmongoosemodels

nodejs express length of list in a model as a response


How can I calculate the length of a list in one of the parameters of a model, and add that length to another parameter of that same model so that it can be send back as part of the response by the api?

const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const ArrayOfUser = require('../models/arrayofuser')

var usersSchema = new Schema({
    items: {type: mongoose.Schema.Types.ObjectId, ref: 'ArrayOfUser'},
    total: items.length

})
module.exports = mongoose.model('Users', usersSchema)

Solution

  • Solution

    These are called virtual properties, functionality directly provided by mongoose:

    Code

    The way to achieve it in your case would be:

    const usersSchema = new Schema({
        items: {type: mongoose.Schema.Types.ObjectId, ref: 'ArrayOfUser'},
    },{
        toObject: {virtuals: true}, toJSON: {virtuals: true}
    })
    
    usersSchema.virtual('total')
        .get(function() {return this.items.length})
    

    Followup to Comments:

    Here is the fixed Node route method for the feedback below! Good luck :)

    //GET array of users data via api
    app.get('/api/v1/users', (req, res) => {
      const pagesToSkip = ~~req.query.pagesToSkip
      const pageSize = ~~req.query.pageSize
      const searchText = req.query.pagesToSkip
      // var searchText = {}
      Users.find().populate('items').exec((err, users) => {
        if (err) {return res.send(err)}
        res.send(users) // I'd recommend `res.json({users})`, but ¯\_(ツ)_/¯
      })
    })
    
    // NOTE: The `~~x` is a code-golfy way of Saying Math.floor(x)