Categories
JavaScript Answers

How to retrieve last inserted id with Node MySQL?

To retrieve last inserted id with Node MySQL, we use the insertedId property.

For instance, we write

connection.query(
  "INSERT INTO posts SET ?",
  { title: "test" },
  (err, result, fields) => {
    if (err) throw err;

    console.log(result.insertId);
  }
);

to call query with a callback that gets the result.insertId property to get the ID of the last inserted item.

Categories
JavaScript Answers

How to fix Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE during PhoneGap installation with Node?

To fix Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE during PhoneGap installation with Node, we disable the strict-ssl option.

To do this, we run

npm config set strict-ssl false

to disable the strict-ssl option to make npm accept untrusted SSL certificates.

Then we run

npm config set strict-ssl true

after installation to turn the certificate check back on.

Categories
JavaScript Answers

How to fix Node npm behind a proxy fails with status 403?

To fix Node npm behind a proxy fails with status 403, we set the registry URL.

To do this, we run

npm config set registry http://registry.npmjs.org/

to set the registry URL with npm config set registry.

Categories
JavaScript Answers

How to log response body with Node Express?

To log response body with Node Express, we use express-winston.

For instance, we write

expressWinston.requestWhitelist.push("body");
expressWinston.responseWhitelist.push("body");
app.use(
  expressWinston.logger({
    transports: [
      new winston.transports.Console({
        json: true,
        colorize: true,
      }),
    ],
    meta: true,
    msg: "HTTP {{req.method}} {{req.url}}",
    expressFormat: true,
    colorStatus: true,
    ignoreRoute: (req, res) => {
      return false;
    },
  })
);

to add a logger with expressWinston.logger.

The meta option lets us set whether to log meta data.

msg is the log entry format.

expressFormat lets us set whether to use the default formatting.

colorStatus lets us set whether to color the log entry.

ignoreRoute lets us set the routes to skip logging for.

Categories
JavaScript Answers

How to fix can’t find documents searching by ObjectId using Node Mongoose?

To fix can’t find documents searching by ObjectId using Node Mongoose, we convert the object ID string to an object ID.

For instance, we write

const ObjectId = require("mongoose").Types.ObjectId;
const query = { campaign_id: new ObjectId(campaign._id) };

to set query to an object with the campaign+id to an object ID that we create by calling the ObjectId constructor with the campaign._id string.