本文介绍了Sequelize - 如何仅返回数据库结果的 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只想返回数据库结果,仅此而已.目前我收到了大量 JSON 数据(如下所示):

So I'm wanting to have the database results returned and nothing else. At the moment I'm getting returned a large chunk of JSON data (Like below):

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

But I'm only needing the [dataValues] attribute. I don't want to have to use the this bit of JSON to retrieve it: tagData[0].dataValues.tagId.

我刚刚注意到:当它找到并且 DOESN'T CREATE 时,它将返回数据库结果的 JSON,但是当它 DOESN'T FIND 并创建,它返回不需要的 JSON blob(如下所示)有没有办法解决这个问题?

I just noticed: When it finds and DOESN'T CREATE, it will return the JSON for the database results, but when it DOESN'T FIND and creates, it returns the un-needed JSON blob (Like below) Is there a way around this?

[ { 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 结果(如下所示),而不是像上面那样得到大块:

Instead of getting the big blob like the above I only need the RAW json results (Like below):

{ 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,但它不起作用?

I've used the following javascript. I did try add raw: true, but it didn't work?

    // 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("
Hashtag has been inserted into DB: ", hashtag);
        }).catch(function(err){
            console.log("
Error inserting tags and relation: ", err);
        });
    }).catch(function(err){
        if(err){
            console.log(err);
        }
    });

}

所以我调查了一下,似乎只有当 Sequelize 正在创建而不是找到时才返回大的 JSON blob.

So I've investigated a bit and it seems that the big JSON blob is only returned when Sequelize is creating and not finding.

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

Is there a way around this or not?

好的,我找到了一种解决方法,可以将其转换为可重复使用的功能.但如果 Sequelize 中内置了一些东西,我更愿意使用它.

Okay so I've found a workaround, which could be turned into a re-usable function. But if there's something built into Sequelize, I'd prefer to use that.

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:

所以,我认为没有官方"的续集方式来实现这一点,所以我只是编写了一个自定义模块,它返回所需的 JSON 数据.该模块可以定制和扩展以适应各种情况!如果有人对如何改进模块有任何建议,请随时发表评论:)

Edit 3:

So, I don't think there is an "Official" sequelize way of achieving this so I simply wrote a custom module which returns the JSON data that's needed. This module can be customised and extended to suit various situations! If anyone has any suggestions to how the module can be improved feel free to comment :)

在这个模块中,我们返回一个 Javascript 对象.如果你想把它变成 JSON 只需使用 JSON.stringify(data) 对其进行字符串化.

In this module we're returning a Javascript Object. If you want to turn it into JSON just stringify it using 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方法.请参阅下面接受的答案.

Edit 4:

So there is an official sequelize method. Refer to the accepted answer below.

推荐答案

虽然文档记录不佳,但 Sequelize 中确实存在这种情况.

Though poorly documented, this does exist in Sequelize.

几种方式:

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

1. For any response object that resulted from a query, you can extract only the data you want by appending .get({plain:true}) the the response like so:

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,它表示是否执行了创建查询.

Also make sure you are using the spread callback function for your type of dynamic query promise. And note that you have access to a boolean response, created, which signifies whether or not a create query was executed.

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

2. Sequelize provides the raw option. Simply add the option {raw:true} and you will receive only the raw results. This will work on an array of results, the first method should not, as get will not be a function of an array.

这篇关于Sequelize - 如何仅返回数据库结果的 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 11:03