【问题标题】:Using Sequelize/Node.js, how can I insert my awkward TEXT datatype into a postgres database?使用 Sequelize/Node.js,如何将笨拙的 TEXT 数据类型插入 postgres 数据库?
【发布时间】:2016-11-29 01:14:17
【问题描述】:

我似乎无法让 Sequelize 允许我将这些尴尬的数据发布到我的 postgres 数据库中。

我最初认为问题是由于文件太大,但是我更新了 bodyParser 以允许 100mb 的数据。

***(下面的例子只是整个文件的sn-p,通常是几百个字符。)

这些数据需要按原样发布到我的数据库中,所以没有正则表达式,也没有重新格式化。

当按照以下示例中的说明保留或尝试将数据用引号括起来时,我收到错误消息“SequelizeValidationError: string violation: data cannot be an array or an object”。

尝试改用 bodyParser.text() 时,我收到错误“SequelizeValidationError: notNull Violation: data cannot be null”。

以下是我正在接收并尝试发布到我的数据库的数据示例:

{
  "data": {"message":{"$":{"version":"CiVI1122","release":"5","xmlns":"http://www.messages.com/messaging"},"header":[{"recipients":[{"to":[{"_":"myname@cutting.cert.messaging.com","$":{"Qualifier":"MESSAGE","FriendlyName":"Joe"}}]}],"from":[{"_":"bob@bob.messag-cert.com","$":{"Qualifier":"MESSAGE","FriendlyName":"BOB"}}],"messageid":["68d3e5d7c97fb3"],"senttime":["2016-05-12T16:05:43.0000000Z"],"sendersoftware":[{"sendersoftwaredeveloper":["Bob'sSoftware"],"sendersoftwareproduct":["Bob's Integration"],"sendersoftwareversionrelease":["0.1"]}],"information":[{"given":["LOY"],"name":["SHMO"],"dob":["1949-04-01"],"gender":["M"],"zip":["77777"]}]}],"body":[{"message":[{"subject":["Message for: Shmo, Joe Sent: 2016-05-12T16:05:43.0000000Z"],"document":[{"plaintext":[""]}],"attachment":[{"documentname":["null"],"file":[{"documenttype":["application/pdf"],"documentdata":["JVBERi0xLjMNCjEgMCBvYmoNClsvUERGIC9UZXh0IC9JbWFnZUIgL0ltYWdlQyAvSW1hZ2VJXQ0KZW5kb2JqDQo3IDAgb2JqDQo8PCAvTGVuZ3RoIDIzNjkgL0ZpbHRlciAvRmxhdGVEZWNvZGUgPj4gc3RyZWFtDQpYCa1a23LbyBF93yr/Q1flIbuJPJo7BnrZkiXH2pS3fBFj11Y2DxAxIhGDAAOA0jJf49f8ZXoGAAlKBHgRy1WUKII9p0+fvsyMX/3wH6CgQ0JBaU1CHoI2AREhFBa+QvYKP+chERAIRTjnII0hXGtghjBtVk+9GcH53wQwRsIwhNE9UCJUgK+aGnw1QkExAY1LcKZh9N4bpRICSQnDL8Tw4+0/3vz97dXoly9vf4LRv2H0F3g7evXDpzUC1DQolJUVPRg=="]}]}]}]}]}}
}

这是我的“消息”模型:

'use strict';

var dateFormat = require('dateformat');

module.exports = function(sequelize, DataTypes) {
  var Surescript = sequelize.define('Message', {
    data: {
      type: DataTypes.TEXT,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    },
    instanceMethods: {
      insertDate: function() {
        return dateFormat(this.createdAt, "dddd, mmmm dS, yyyy, h:MM TT")
      }
    }
  });
  return Message;
};

这是我的 POST 路线:

router.post('/', utils.auth, function(req, res, next) {
  var currentUser = auth(req);
  UserModel.findOne({
    where: { username: currentUser.name, password: currentUser.pass }
  }).then(function(user) {
    if (user.username == currentUser.name && user.password == currentUser.pass && user.admin == true) {
      MessageModel.create({
        data: req.body.data
      })
      res.send('POST');
    }
  })
  .then(function() {
    res.end();
  })
  .catch(function(err) {
    res.sendStatus(401);
  });
});

我的 server.js 文件中有这段代码:

app.use(methodOverride('_method'));
app.use(logger('dev'));
app.use(bodyParser.json({limit: '100mb'}));
app.use(bodyParser.urlencoded({ limit: '100mb', extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

到目前为止,我已经尝试将消息模型中的数据类型从 TEXT 更改为 JSON 到 BLOB,但是这些更改导致了同样的问题。

非常感谢任何帮助!!!

【问题讨论】:

    标签: node.js postgresql express sequelize.js body-parser


    【解决方案1】:

    如果这是正确有效的 JSON,您可能需要检查以下 Sequelize 类型:

    http://docs.sequelizejs.com/en/v3/api/datatypes/json

    或者

    http://docs.sequelizejs.com/en/v3/api/datatypes/jsonb

    在 postgresql 中加上正确的类型:

    https://www.postgresql.org/docs/9.4/static/datatype-json.html

    关于 JSON 字段的另一个很棒的注意事项是,它本身被视为 No-SQL 数据库,因此您可以对字段本身进行一些很酷的查询进入

    编辑: 另外,我注意到您仍然对 JSON 有疑问;在尝试存储该对象之前,对它进行 JSON.stringify 非常重要。这可能是问题的根源,因为它不想存储对象,而是对象的文本表示。

    【讨论】:

    • 噢!是的。 JSON.Stringify。我会试一试。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2020-09-03
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2020-09-28
    相关资源
    最近更新 更多