Sequelize - 我怎样才能 return JSON 数据库结果的唯一对象?

Sequelize - How can I return JSON objects of the database results only?

所以我想要 returned 数据库结果,除此之外别无其他。目前我正在 return 编辑大量 JSON 数据(如下所示):

但我只需要 [dataValues] 属性。我不想使用 JSON 的这一点来检索它:tagData[0].dataValues.tagId.

我刚刚注意到:当它发现 DOESN'T CREATE 时,它将 return JSON 用于数据库结果,但是当它 找不到并创建,它return是不需要的JSON blob(如下所示)有解决办法吗?

[ { dataValues:
     { tagId: 1,
       tagName: '#hash',
       updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),
       createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },
    _previousDataValues:
     { tagId: 1,
       tagName: '#hash',
       createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),
       updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },
    _changed:
     { tagId: false,
       tagName: false,
       createdAt: false,
       updatedAt: false },
    '$modelOptions':
     { timestamps: true,
       instanceMethods: {},
       classMethods: {},
       validate: {},
       freezeTableName: true,
       underscored: false,
       underscoredAll: false,
       paranoid: false,
       whereCollection: [Object],
       schema: null,
       schemaDelimiter: '',
       defaultScope: null,
       scopes: [],
       hooks: {},
       indexes: [],
       name: [Object],
       omitNull: false,
       sequelize: [Object],
       uniqueKeys: [Object],
       hasPrimaryKeys: true },
    '$options':
     { isNewRecord: true,
       '$schema': null,
       '$schemaDelimiter': '',
       attributes: undefined,
       include: undefined,
       raw: true,
       silent: undefined },
    hasPrimaryKeys: true,
    __eagerlyLoadedAssociations: [],
    isNewRecord: false },
  true ]

我只需要 RAW json 结果(如下所示),而不是像上面那样得到大斑点:

{ tagId: 1,
       tagName: '#hash',
       updatedAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT),
       createdAt: Fri Dec 25 2015 17:07:13 GMT+1100 (AEDT) },

我使用了以下 javascript。我确实尝试添加 raw: true,但没有成功?

    // Find or create new tag (hashtag), then insert it into DB with photoId relation
module.exports = function(tag, photoId) {
    tags.findOrCreate( { 
        where: { tagName: tag },
        raw: true
    })
    .then(function(tagData){
        // console.log("----------------> ", tagData[0].dataValues.tagId);
        console.log(tagData);
        tagsRelation.create({ tagId: tagData[0].dataValues.tagId, photoId: photoId })
        .then(function(hashtag){
            // console.log("\nHashtag has been inserted into DB: ", hashtag);
        }).catch(function(err){
            console.log("\nError inserting tags and relation: ", err);
        });
    }).catch(function(err){
        if(err){
            console.log(err);
        }
    });

}

编辑:

所以我调查了一下,似乎大 JSON blob 仅在 Sequelize 正在创建但未找到时 returned。

有没有办法解决这个问题?

编辑 2:

好的,我找到了一个解决方法,它可以变成一个可重复使用的函数。但是,如果 Sequelize 中内置了一些东西,我更愿意使用它。

var tagId = "";

// Extract tagId from json blob
if(tagData[0].hasOwnProperty('dataValues')){
    console.log("1");
    tagId = tagData[0].dataValues.tagId;
} else {
    console.log("2");
    console.log(tagData);
    tagId = tagData[0].tagId;
}

console.log(tagId);
tagsRelation.create({ tagId: tagId, photoId: photoId })

编辑 3:

所以,我认为没有 "Official" sequelize 方法可以实现这一点,所以我只是编写了一个自定义模块,其中 return 包含所需的 JSON 数据。该模块可以定制和扩展以适应各种情况!如果有人对如何改进模块有任何建议,请随时发表评论:)

在本模块中,我们将 return 创建一个 Javascript 对象。如果你想把它变成 JSON 只需使用 JSON.stringify(data) 将它字符串化。

// Pass in your sequelize JSON object
module.exports = function(json){ 
    var returnedJson = []; // This will be the object we return
    json = JSON.parse(json);


    // Extract the JSON we need 
    if(json[0].hasOwnProperty('dataValues')){
        console.log("HI: " + json[0].dataValues);
        returnedJson = json[0].dataValues; // This must be an INSERT...so dig deeper into the JSON object
    } else {
        console.log(json[0]);
        returnedJson = json[0]; // This is a find...so the JSON exists here
    }

    return returnedJson; // Finally return the json object so it can be used
}

编辑 4:

所以官方有sequelize方法。请参阅下面已接受的答案。

如果您只想使用 values of an instance 尝试调用 get({plain: true})toJSON()

tags.findOrCreate( { 
    where: { tagName: tag }
})
.then(function(tagData){
     console.log(tagData.toJSON());
})

虽然记录不多,但在 Sequelize 中确实存在。

情侣方式:

1. 对于查询产生的任何响应 object,您可以通过附加 .get({plain:true}) 响应如下:

Item.findOrCreate({...})
      .spread(function(item, created) {
        console.log(item.get({
          plain: true
        })) // logs only the item data, if it was found or created

还要确保您使用的是 spread 回调函数作为您的动态查询承诺类型。请注意,您可以访问布尔响应 created,它表示是否执行了创建查询。

2. Sequelize 提供了raw选项。只需添加选项 {raw:true},您将只收到原始结果。这将适用于结果数组,第一种方法不应该,因为 get 不是数组的函数。

sequelize-values 是一个 npm 模块,可以帮助你做到这一点。它有一些方法可以轻松地在单个项目和结果列表(数组)上打印值 https://www.npmjs.com/package/sequelize-values

更新:

使用data.dataValues

db.Message.create({
    userID: req.user.user_id,
    conversationID: conversationID,
    content: req.body.content,
    seen: false
  })
  .then(data => {
    res.json({'status': 'success', 'data': data.dataValues})
  })
  .catch(function (err) {
    res.json({'status': 'error'})
  })

现在使用 async/await 语法更易于阅读

module.exports = async function(tagName) {
  const [tag, created] = await Tag.findOrCreate({
    where: {tagName},
    defaults: {tagName}
  });
  return tag.get({plain:true});
}