所以我只想返回数据库结果,别的什么都不想.目前,我收到了一大块JSON数据(如下所示):

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.

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 ]

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,但没用?

    // 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);
        }
    });

}

编辑:

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

有没有办法绕过这件事?

Edit 2:

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 })

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 :)

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:

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

推荐答案

Though poorly documented, this does exist in 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,它表示是否执行了create查询.

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

Json相关问答推荐

如何使用ChoETL将复杂的JSON转换为CSV

我如何知道TJSONNumber是double还是double?

解析SQL中的嵌套JSON

如何将文件夹组织的.json文件合并为一个JSON文件,文件夹/文件名作为键

从字节解码 JSON 数据,将 float 值更改为 int

提交后使用 Rails 7 结合 JSON 标签进行标记

从 json 对象中过滤掉所有出现的给定属性

如何在 jQuery 中循环遍历 JSON 数组?

.NET 对象最灵活的序列化是什么,但实现起来很简单?

Android JSON 库的性能和可用性比较

字符串的 Gson 数组到 JsonArray

错误未判断调用put(K, V)作为原始类型java.util.HashMap的成员

如何使用 Jackson 注释从 HttpResponse 反序列化 JSON 对象?

使用 JSON.Net 的 C# 到 JSON 序列化

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器

如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性

将多个值存储在json中的单个键中

XML vs YAML vs JSON

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?

JSON键是否需要唯一?