首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Sequelize -如何只返回数据库结果的JSON对象?

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

Stack Overflow用户
提问于 2015-12-25 14:11:54
回答 5查看 39.7K关注 0票数 35

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

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

我刚刚注意到:当它找到并且没有创建时,它会返回数据库结果的JSON,但是当它没有找到并创建时,它会返回不需要的JSON blob (如下所示)。有什么方法可以解决这个问题吗?

代码语言:javascript
复制
[ { 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结果(如下所示),而不是像上面这样得到大的斑点:

代码语言:javascript
复制
{ 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,但它不起作用?

代码语言:javascript
复制
    // 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。

有没有办法绕过这个问题?

编辑2:

好的,我找到了一个变通方法,它可以变成一个可重用的函数。但如果Sequelize中内置了什么,我更喜欢使用它。

代码语言:javascript
复制
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)将其串化即可。

代码语言:javascript
复制
// 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方法。请参考下面接受的答案。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-01-23 18:26:36

尽管文档很少,但Sequelize中确实存在这一点。

有几种方式:

1.对于查询产生的任何响应object,您可以通过将响应附加到.get({plain:true})来仅提取所需的数据,如下所示:

代码语言:javascript
复制
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不是一个数组的函数。

票数 32
EN

Stack Overflow用户

发布于 2015-12-25 21:27:37

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

代码语言:javascript
复制
tags.findOrCreate( { 
    where: { tagName: tag }
})
.then(function(tagData){
     console.log(tagData.toJSON());
})
票数 12
EN

Stack Overflow用户

发布于 2018-09-30 17:00:44

更新:

使用data.dataValues

代码语言:javascript
复制
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'})
  })
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34460482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档