nodejs 将模型中列表的长度表示为响应

nodejs express length of list in a model as a response

我如何计算模型的一个参数中列表的长度,并将该长度添加到同一模型的另一个参数中,以便它可以作为响应的一部分由 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)

解决方案

这些被称为virtual properties,由mongoose直接提供的功能:

代码

在你的情况下实现它的方法是:

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})

跟进评论:

这里是下面反馈的固定Node路由方法!祝你好运 :)

//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)