【问题标题】:Calling a mysql column using template literals node js使用模板文字节点js调用mysql列
【发布时间】:2020-09-13 17:01:28
【问题描述】:

我正在尝试使用模板文字从我的节点 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

      });
    });

  }
}

【问题讨论】:

  • 我无法识别服务中查询中使用的此模板语法。你能解释一下吗?
  • 那么消息在哪里说:Post ${body.post_id} was successfully created 我正在尝试在成功创建后输入帖子 ID。我希望从 mysql 中提取 post_id

标签: javascript mysql node.js express


【解决方案1】:

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

【讨论】:

  • @ForestProgramming
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 2012-09-28
相关资源
最近更新 更多