質問

According to the node-mysql documentation, the result of inserting a row into a table with an auto_increment primary key is an object, one of whose fields is insertId. However, I do not see this in running the code below. Instead, I see that the result is a two element array, whose first element is an object of the desired type, but whose second element is undefined. In particular, the code below prints:

[ { fieldCount: 0,
    affectedRows: 1,
    insertId: 12,
    serverStatus: 2,
    warningCount: 0,
    message: '',
    protocol41: true,
    changedRows: 0 },
  undefined ]

Can anyone explain this discrepancy between the docs and the observed behavior?

Code:

var mysql = require("mysql")
var Q = require("q")


var db = {
        "host": "localhost",
        "user": "root",
        "password": "xyz",
        "database": "study"
}

var pool  = mysql.createPool(db);
var getConnection = Q.nbind(pool.getConnection, pool)

getConnection().then(function (connection) {
    Q.ninvoke(connection, 'query', "insert into tsheet (cname) values('reformation');")
        .then(
            function (rslt) {
                console.log(rslt)
                process.exit(0)
            })
}).done()

Here is the table:

mysql> describe tsheet;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| cid   | int(11)      | NO   | PRI | NULL    | auto_increment |
| cname | varchar(256) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
役に立ちましたか?

解決

node-mysql expects a callback with three parameters: err, rows, fields. Q is taking the latter two of those parameters and putting them into an array so the next function is called with only one parameter. (err is handled separately in .catch). Since this is an INSERT, the fields parameter is undefined.

If you want to take both of those parameters separately, use .spread:

Q.ninvoke(connection, 'query', "insert into tsheet (cname) values('reformation');")
  .spread(
    function (rslt, fields) {
      console.log(rslt)
      process.exit(0)
    });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top