猫鼬静态函数“ realization.fetchTotalPointsPerChild”不是一个函数

时间:2020-03-09 20:17:18

标签: node.js mongoose-schema

我想从一个模型的聚合函数中得到一些结果,但出现类似以下错误:

realization.fetchTotalPointsPerChild不是函数

这是我的文件:

这是我的架构: realization.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const actionSchema = new Schema({
    type: {
        type: String,
        required: true
    },
    point: {
        type: Number,
        min: -1001,
        max: 1001,
        required: true
    },
    pointType: {
        type: String,
        required: true
    },
    goal:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Goals'
    }, 
    penalty: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Penalty'
    }
},{
    timestamps: true
})

const realizationSchema = new Schema({
    child: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Child'
    },
    actions: [actionSchema]
},
{
    timestamps: true
});

realizationSchema.statics.fetchTotalPointsPerChild = function(callback) {
    return this.aggregate([
        { $unwind: "$actions" },
        {
            $group: {
                _id: null,
                totalPointsPerChild: {
                    $sum: "$actions.point"
                }
            }
        }
    ], function(err, result) {
        if (err) callback(err);
        callback(result)
    })
}

module.exports = mongoose.model('Realization', realizationSchema);

这是我的路由器: realizationRouter.js

const express = require('express');
const bodyParser = require('body-parser');
const Realization = require('../models/realization');

const realizationRouter = express.Router();

realizationRouter.use(bodyParser.json());

realizationRouter.route('/:childId/actions/totalPoints')
.get((req, res, next) => {
    Realization.findOne({child: req.params.childId})
    .populate('goals')
    .populate('penalty')
    .then(realization => {
        if(realization) {
            realization.fetchTotalPointsPerChild((err, result) => {
                if(err){
                    next(err);
                }
                res.statusCode = 200;
                res.setHeader('Content-Type', 'application/json');
                res.json(result);
            })
        } else {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'application/json');
            res.json(`There is no action to show from this child ${req.params.childId}`);
        }
    })
    .catch(err => next(err));
});

我已经尝试过将静态变量替换为方法或实例的更改,但对我而言,更有意义的是静态变量,但我不断遇到相同的错误。请有人知道我在这里想念的吗?

1 个答案:

答案 0 :(得分:1)

if(realization) {
   realization.fetchTotalPointsPerChild((err, result) => {
   if(err){
   next(err);
   }
   res.statusCode = 200;
   res.setHeader('Content-Type', 'application/json');
   res.json(result);
})

我认为您对realization变量感到困惑。实现变量是查询的结果。返回的不是您的模型,因此没有功能。静态可以直接在模型上使用,因此Realization.fetchTotalPointsPerChild()...