Sequelize-如何仅返回数据库结果的JSON对象?

詹姆斯111:

因此,我想返回数据库结果,而别无其他。目前,我返回了大量的JSON数据(如下所示):

但是我只需要[dataValues]属性。我不需要使用以下代码JSON来检索它:tagData[0].dataValues.tagId

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

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

{ 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。我确实尝试了add 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只有在Sequelize创建而不是查找时才返回大块

有没有解决的办法?

编辑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:

因此,我认为没有实现此目的的“正式”续集方式,因此我只写了一个自定义模块即可返回所需JSON数据。该模块可以定制并扩展以适应各种情况!如果有人对如何改进该模块有任何建议,请随时评论:)

在此模块中,我们将返回一个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中确实存在。

几种方式:

1.对于由查询产生的任何响应对象,您可以通过添加.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不是数组的函数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章