javascript - 查询结果未定义

标签 javascript mysql node.js unit-testing

exports.save = function(req, res) {

connection.query('INSERT INTO student_details(name, course, units, grades, gwa) VALUES(?, ?, ?, ?, ?)',[req.body.name,req.body.course,req.body.units,req.body.grades,req.body.gwa], function(err, row) {
    if(err) res.send('Error in query');
    selectOne(row.insertId, function(newRow){
        if(err) res.status(554).send('Error in query');
        if(newRow == null){
            res.send(552, {message: 'Student Details ('+row.insertId+') was not created.'});
        } else{
            res.status(200).send(newRow);
        }
    });
});

}

var selectOne = function(id, callback){

connection.query('SELECT * FROM student_details WHERE id=? LIMIT 1', [id], function(err, rows){
    if(err) return err;
    if(rows.length != 0){
        callback(rows[0]);
    }else{
        callback(null);
    }
});
}

我在执行上述查询时遇到错误。它说这个错误:

Uncaught TypeError: Cannot read property 'insertId' of undefined.

几个小时以来,我一直在努力解决这个问题,我的直觉是它与异步值有些相关,但我不知道如何解决它。

更新:

这是我的测试文件:

    var studentdb = require(__dirname + '/../studentdb'),
    student = require(__dirname + '/../student'),
    index = require(__dirname + '/../index'),
    should = require('should-http'),
    assert = require('assert'),
    request = require('supertest');

describe('Student Details', function() {
    var url = 'http://localhost:1337';
    var randomName = student.getRandomName(10);
    var insertedId = 0;
    describe('insert()', function () {
    it('should create a new student record', function (done) {
            var input = {
                nameLength: 10,
                subjectsLength: 5,
                course: 'CAS'
        };
        studentName = student.getRandomName(input.nameLength);
        studentCourse = student.getRandomCourse(input.course);
        studentUnits = student.getRandomUnits(input.subjectsLength);
        studentGrades = student.getRandomGrades(input.subjectsLength);
        studentGWA = student.computeGWA(studentUnits, studentGrades,input.subjectsLength);
        var stringUnits = studentUnits.join();
        var stringGrades = studentGrades.join();
        var generatedStudent = {
            'name': studentName,
            'course': studentCourse,
            'units': stringUnits,
            'grades': stringGrades,
            'gwa': studentGWA
        }
        request(url)
            .post('/addStudent')
            .send(generatedStudent)
            .end(function(err, res) {
                if (err) {
                    throw err;
                }
                res.should.have.status(200);
                res.body.should.have.keys(['id', 'name', 'course','units', 'grades', 'gwa']);
                done();
            });
        });
    });
    describe('save()', function() {
        console.log(insertedId);
        it('should generate a student record', function(done) {
            request(url)
                .get('/generateStudent')
                .end(function(err, res) {
                    if(err) throw err;
                    res.should.have.status(200);
                    res.body.should.not.have.property('name', null);
                    res.body.should.not.have.property('course', null);
                    generatedStudent = res.body;
                    done();
                });
        });
        it('should not have duplicate name', function(done) {
            request(url)
                .get('/getStudents')
                .end(function(err, res) {
                    if(err) throw err;
                    res.body.forEach(function(iteration) {
                        assert.notEqual(iteration, generatedStudent.name);
                    });
                    done();
                });
        });
        it("now adding to the database", function(done) {
            request(url)
                .post('/addStudent')
                .send(generatedStudent)
                .end(function(err, res) {
                    if(err) throw err;
                    res.body.should.have.status(200);
                    console.log(res.body.id);
                    res.body.should.have.keys(['id', 'name', 'course', 'units', 'grades', 'gwa']);
                    done();
                });
        });
    });
});

------------遵循 Zeeshan 的代码后的第二次更新---------------- 他们一直在评论部分拒绝我的修改。

同样,我已经尝试了你的建议,但仍然没有雪茄。我还打印了“newRow”以表明正在正确检索数据,只是当我尝试 res.send 函数时,它被读取为未定义,因此导致错误。感谢您的耐心等待!

Server Connected on port:  1337


  Student Details
    insert()
Database is connected ... nn
If error, I should not be printed
Value of row.insertId  34
{ id: 34,
  name: 'H3tno72Osk',
  course: 'BS Computer Science',
  units: '4,1,2,4,2',
  grades: '3.0,3.0,3.0,3.0,4.0',
  gwa: 3 }
      ✓ should create a new student record (66ms)
    save()
      ✓ should generate a student record
      ✓ should not have duplicate name
      1) now adding to the database


  3 passing (90ms)
  1 failing

  1) Student Details save() now adding to the database:
     Uncaught AssertionError: expected Object { body: undefined, statusCode: undefined } to have property statusCode of 200 (got undefined)
      at Assertion.fail (node_modules/should/lib/assertion.js:92:17)
      at Assertion.Object.defineProperty.value [as status] (node_modules/should/lib/assertion.js:164:19)
      at Test.<anonymous> (test/studentdb.js:86:27)
      at Test.assert (node_modules/supertest/lib/test.js:156:6)
      at assert (node_modules/supertest/lib/test.js:127:12)
      at node_modules/supertest/lib/test.js:124:5
      at Test.Request.callback (node_modules/supertest/node_modules/superagent/lib/node/index.js:691:12)
      at IncomingMessage.<anonymous> (node_modules/supertest/node_modules/superagent/lib/node/index.js:922:12)
      at _stream_readable.js:920:16

最佳答案

稍微修改一下,您也可以尝试一下并更新结果吗?

exports.save = function(req, res) {

connection.query('INSERT INTO student_details(name, course, units, grades, gwa) VALUES(?, ?, ?, ?, ?)',[req.body.name,req.body.course,req.body.units,req.body.grades,req.body.gwa], function(err, row) {
    if(err) return res.send('Error in query');
    console.log("If Errror I should not pe printed");
    console.log("Value of row.insertId ", row.insertId);
    selectOne(row.insertId, function(newRow, insertId){
        if(err) res.status(554).send('Error in query');
        if(newRow == null){
            res.send(552, {message: 'Student Details ('+insertId+') was not created.'});
        } else{
            res.status(200).send(newRow);
        }
    });
});

}

var selectOne = function(id, callback){

connection.query('SELECT * FROM student_details WHERE id=? LIMIT 1', [id], function(err, rows){
    if(err) return err;
    if(rows.length != 0){
        callback(rows[0], id);
    }else{
        callback(null, id);
    }
});

}

关于javascript - 查询结果未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371763/

相关文章:

node.js - MongoDb 与 Node js 的连接

javascript - 不了解此 Canvas 代码的工作原理

javascript - 使用 mobx-react-lite 和 React hooks 在 React Native 中获取函数

mysql - 设置列的范围

node.js - 在 Q 中链接任意数量的 promise

node.js - 如何收缩使用 'npm link' 创建的符号链接(symbolic link) Node 模块?

javascript - 如何将 css 样式表和 js 文件调用到自定义 WordPress 主题中

javascript - Ember.js - 如何在另一个服务中使用一个服务?

时间:2019-03-17 标签:c#-System.FormatException: 'Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'

mysql - 使用 SELECT 和 JOIN 语句将多个数据插入表中