首页 > 解决方案 > 使用模板文字节点js调用mysql列

问题描述

我正在尝试使用模板文字从我的节点 js 文件中的 mysql 调用一个字段,但无法获取该值。请查看下面的 post.controller.js 文件,其中显示消息:Post ${body.post_id} was successfully created其中 post_id 是我的 mysql 数据库中的一个字段。

//以下代码在post.service.js文件中

const pool = require("../../config/database");

module.exports = {

  //Create new post
  createPost: (data, callBack) =>{
    pool.query(
      `insert into posts(userhandle, post_body)
              values(?,?)`,
    [
      data.userhandle,
      data.post_body
    ],
    (error, results, fields) =>{
      if(error){
        return callBack(error);
      }
      return callBack(null, results);
    }
    );
  }
}

//以下代码在post.controller.js文件中

const {
  createPost,
} = require("./post.service");


module.exports = {

  //Controller for creating new post
  createPost: (req, res) =>{
    const body = req.body;
    createPost(body, (err, results) => {
      if(err){
        console.log(err);
        return res.status(500).json({
          success:0,
          message:"Error. Unable to create post"
        });
      }
      return res.status(200).json({
        success: 1,
        message: `Post ${body.post_id} was successfully created`,
        data: results

      });
    });

  }
}

标签: javascriptmysqlnode.jsexpress

解决方案


我猜 post_id 是一个 PK 自动递增,如果是这样 try results.post_id,因为这是一个从回调中重新调整的对象。如果这不起作用console.log(results),请查看 post_id 是否在其中。


推荐阅读