UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“结果”

时间:2019-07-29 12:14:18

标签: node.js mongodb

我要创建api,从那里手动找到学生成绩并比较成绩

我有两个集合studentsubject都与参考ID相关联

这是我的app.js

 app.js

var express = require('express');
var mongoose = require('mongoose');
var app = express();
var school = require('./controllers/school_controller');
var port = 3000;
var http = require('http');


mongoose.connect(
    'mongodb://localhost:27017/company-info',
    {useNewUrlParser: true},
    err => {
        if(err) throw err;
        console.log('connection successfully');
    }
)

app.set('secreteKey', 'company-info');
app.use(cors({ maxAge: 600 }));
app.use(express.json());
app.use(express.urlencoded({extended: true}));

app.use('/school', school);


http.createServer(app).listen(port, function(req, res){
    console.log('start your server on: ', port);
}); 

这是我的模特

models/school.js

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const mongooseHidden = require('mongoose-hidden')()

var validateEmail = function(email) {
    var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    return re.test(email)
};

var adminSchema = new mongoose.Schema({
    name: { type: String, required: "name is require"},
    mobile_no: { type: String,  minlength: 10, maxlength: 14, required: "mobile_no is require"},
    user_type: { type: String},
    email: { 
        type: String,
        required: 'email is require',
        lowercase: true,
        unique: true,
        validate: [validateEmail, 'Please fill a valid email address'] 
    },
    password: {
        type: String,
        required: true,
        hide: true
    }
});
adminSchema.pre('save',function(next){
    this.password = bcrypt.hashSync(this.password, saltRounds);
    next();
});
adminSchema.plugin(mongooseHidden);
adminSchema.plugin(uniqueValidator);
var admin = mongoose.model("admin", adminSchema);


var principleSchema = new mongoose.Schema({
    name: { type: String, required: "name is require"},
    mobile_no: { type: String, minlength: 10, maxlength: 14, required: "mobile_no is require"},
    degree: { type: String,  required: "degree is require"},
    user_type: { type: String,  required: true },
    email: { 
        type: String,
        required: true,
        lowercase: true,
        unique: true,
        validate: [validateEmail, 'Please fill a valid email address'] 
    },
    password: {
        type: String,
        required: true,
        hide: true
    }
});
principleSchema.pre('save',function(next){
    this.password = bcrypt.hashSync(this.password, saltRounds);
    next();
});
principleSchema.plugin(mongooseHidden);
principleSchema.plugin(uniqueValidator);
var principle = mongoose.model("principle", principleSchema);


var teacherSchema = new mongoose.Schema({
    // _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: "name is require"},
    mobile_no: { type: String,  minlength: 10, maxlength: 14, required: "mobile_no is require"},
    class: { type: Number, required: "class is require" },
    user_type: { type: String },
    degree: { type: String, required: "degree is require" },
    email: { 
        type: String,
        required: 'email is require',
        lowercase: true,
        unique: true,
        validate: [validateEmail, 'Please fill a valid email address'] 
    },
    password: {
        type: String,
        required: true,
        hide: true
    }
});
teacherSchema.pre('save',function(next){
    this.password = bcrypt.hashSync(this.password, saltRounds);
    next();
});
teacherSchema.plugin(mongooseHidden);
teacherSchema.plugin(uniqueValidator);
var teacher = mongoose.model("teacher", teacherSchema);


var studentSchema = new mongoose.Schema({
    name: { type: String, required: "name is require"},
    roll_no: {type: Number, required: "roll_no is require"},
    class: { type: Number, require: "class is require"},
    user_type: { type: String },
    email: { 
        type: String,
        required: 'email is require',
        lowercase: true,
        unique: true,
        validate: [validateEmail, 'Please fill a valid email address'] 
    },
    password: {
        type: String,
        required: true,
        hide: true
    }
});
studentSchema.pre('save',function(next){
    this.password = bcrypt.hashSync(this.password, saltRounds);
    next();
});
studentSchema.plugin(mongooseHidden);
studentSchema.plugin(uniqueValidator);
var student = mongoose.model("student", studentSchema);


var subjectSchema = new mongoose.Schema({
    result: [{ subject: String, marks: Number }],
    student_id: { type: mongoose.Schema.Types.ObjectId, ref: 'student'}
});
subjectSchema.plugin(mongooseHidden, { hidden: { student_id: true}});
var subject = mongoose.model("subject", subjectSchema);


module.exports = { admin: admin, principle: principle, teacher: teacher, student: student, subject: subject }

这是我的控制者:

controllers/school_controller.js

var express = require('express');
var router = express.Router();
var school = require('../models/school');

router.get('/subject_pass',  function(req, res){
     school.student.find({ class: req.body.class}, async function(err, data){
            if(err){
                res.send(err);
            } else {
              //  res.send(data);
             // console.log(data);
              for(var i = 0; i <= 4; i++){
               // console.log(data[i]._id);
               await school.subject.find({ student_id: data[0]._id}, async function(err, info) {
                    if (err) {
                        res.send(err);
                    } else {
                            console.log(info);
                            for(var k = 0; k <= 2; k++){
                            console.log(info[i].result[k].subject)
                            console.log(info[i].result[k].marks)
                        }
                      await school.subject.aggregate([{ $match: { subject: req.body.subject }}], function(err, details){
                        if(err){
                            res.send(err);
                        } else {
                            console.log(details);
                        }
                    })
                    }
                });
            }       
        }
    })
})

 module.exports = router;

我正在尝试很多方法,但是我的for(var i = 0; i <= 4; i++)无法正常工作,这会产生错误。

1 个答案:

答案 0 :(得分:0)

无论何时使用school.student.find({ class: req.body.class}, ...)搜索主题,它都会在student变量中返回info文档。

根据映射,信息应包含> = 0个条目,因此索引将从0开始,例如: info[0]info[1]

但在代码中

for(var k = 0; k <= 2; k++){
  console.log(info[i].result[k].subject)
  console.log(info[i].result[k].marks)
}

i是0到4。因此,假设您位于i的最后一个i=3处。但是info变量MAY或MAY不能包含4th元素。

这就是为什么info[i]索引中没有元素时3rd抛出未定义的原因。

基本上,如果您的主题仅包含1个主题,则可以使用0代替i

for(var k = 0; k <= 2; k++){
  console.log(info[0].result[k].subject);
  console.log(info[0].result[k].marks);
}

或者如果有多个info

info.forEach((infoElement)=>{
    for(var k = 0; k <= 2; k++){
      console.log(infoElement.result[k].subject);
      console.log(infoElement.result[k].marks);
    }
});