当前位置: 首页 > 知识库问答 >
问题:

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

荀辰钊
2023-03-14

我是板条箱获取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;

我尝试了很多方法,但我的(var I=0;I<=4;I++)不能正常工作,这将产生错误。

共有1个答案

佟云
2023-03-14

每当您使用school.student.find({class:req.body.class},...)搜索科目时,它将返回info变量中的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变量可能包含也可能不包含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.forEach((infoElement)=>{
    for(var k = 0; k <= 2; k++){
      console.log(infoElement.result[k].subject);
      console.log(infoElement.result[k].marks);
    }
});
 类似资料:
  • (节点:55028)UnhandledPromiserEjectionWarning:TypeError:无法读取位于/users/PatrickStanciu/WebStormProjects/AUTISMAssistant/Backend/API/Controllers/PaymentsController.js:1045:34 位于processTicksAndRejections(inte

  • 我正在尝试使用node express和Mongoose创建用户登录和注册...创建了用户模型....现在尝试在我的路由器auth.js中添加一个post方法,但由于某种原因,我一直得到错误不能读取属性'name'的未定义昨天我写了完全相同的代码,但使用了一些其他post方法,结果非常好.... 我只想让邮递员的工作现在就这样...多谢 auth.js文件 user.js文件 在此输入图像说明

  • 机器人随机崩溃并发出此错误。我已经将它编程为每当有问题时自动重新启动,并记录错误,因为它的技术上意味着不关机。 用于自动重新启动的代码如下: 我似乎也被“未经处理的承诺拒绝”...

  • 为什么我得到这个错误不能读取未定义的触摸属性? 为什么它不能读取,但它可以读取 当我们使用

  • 问题内容: 我正在制作非常简单的react应用。但是,当我尝试通过onChange事件调用父(实际上是祖父母)组件的方法时,我一直在获取。 这是触发事件的组件/表单(因此,在绑定的父组件上调用方法…是的,因为我通过道具将其从父组件传递下来,所以在方法上使用了.bound(this)。) 这是我如何通过大多数父(祖父母)组件中的props传递该方法的方法。 这是我作为父项(方法所有者和方法调用程序之

  • 我正在测试发送电子邮件与流星js和nodemailer插件: 流星添加捷运:流星NodeEmailer 当页面加载时,我在导航器的控制台上看到错误:无法读取未定义的属性“创建运输”。 那么问题是什么呢? 代码如下: /////////////////////////////////////////// ///////////////