Sequelize-如何仅返回数据库结果的JSON对象? [英] Sequelize - How can I return JSON objects of the database results only?

查看:211
本文介绍了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.

我刚刚注意到:找到并不创建时,它将为数据库结果返回JSON,但是当它不查找并且创建后,它返回不需要的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 ]

与其像上面那样获得较大的Blob,我只需要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("\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);
        }
    });

}

因此,我进行了一些调查,似乎只有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 })

因此,我认为没有实现此目的的正式"续集方式,因此我只编写了一个自定义模块,该模块返回所需的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
}

因此,有一种官方的续集方法.请参阅下面接受的答案.

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..对于查询产生的任何响应对象,您可以通过将.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对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆