Javascript Sequelize - 如何仅返回数据库结果的 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34460482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sequelize - How can I return JSON objects of the database results only?
提问by James111
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):
所以我想要返回数据库结果而不是别的。目前我正在返回一大块 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
.
但我只需要 [dataValues] 属性。我不想使用 this bitJSON
来检索它: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 FINDand creates, it returns the un-needed JSON blob (Like below) Is there a way around this?
我刚刚注意到:当它找到并且DOESN'T CREATE 时,它将返回JSON
数据库结果,但是当它DOESN'T FIND并创建时,它返回不需要的 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 ]
Instead of getting the big blob like the above I only need the RAW
json results (Like below):
而不是像上面那样得到大 blob,我只需要RAW
json 结果(如下所示):
{ 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) },
I've used the following javascript. I did try add raw: true
, but it didn't work?
我使用了以下 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);
}
});
}
Edit:
编辑:
So I've investigated a bit and it seems that the big JSON
blob is only returned when Sequelize
is creating and not finding.
因此,我进行了一些调查,似乎JSON
只有在Sequelize
创建而不是查找时才返回大blob 。
Is there a way around this or not?
有没有办法解决这个问题?
Edit 2:
编辑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.
好的,所以我找到了一个解决方法,它可以变成一个可重用的功能。但是如果有内置的东西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 })
Edit 3:
编辑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 :)
所以,我不认为有一种“官方”的续集方式可以实现这一点,所以我只是编写了一个自定义模块来返回JSON
所需的数据。该模块可以定制和扩展以适应各种情况!如果有人对如何改进模块有任何建议,请随时发表评论:)
In this module we're returning a Javascript Object. If you want to turn it into JSON
just stringify it using JSON.stringify(data)
.
在这个模块中,我们返回一个 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
}
Edit 4:
编辑4:
So there is an official sequelize method. Refer to the accepted answer below.
所以有官方的sequelize方法。请参阅下面已接受的答案。
采纳答案by rambossa
Though poorly documented, this does exist in Sequelize.
尽管记录不足,但这确实存在于 Sequelize 中。
Couple Ways:
情侣方式:
1.For any response objectthat resulted from a query, you can extract only the data you want by appending .get({plain:true})
the the response like so:
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
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.
还要确保您正在spread
为您的动态查询承诺类型使用回调函数。请注意,您可以访问布尔响应,created
,它表示是否执行了创建查询。
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.
2.Sequelize 提供了raw
选项。只需添加选项{raw:true}
,您将只收到原始结果。这将适用于结果数组,第一种方法不应该,因为get
不会是数组的函数。
回答by Rudolf Manusachi
If you want to work only with the values of an instancetry to call get({plain: true})
or toJSON()
如果您只想使用实例的值,请尝试调用get({plain: true})
或toJSON()
tags.findOrCreate( {
where: { tagName: tag }
})
.then(function(tagData){
console.log(tagData.toJSON());
})
回答by KitKit
Updated:
更新:
Use data.dataValues
用 data.dataValues
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'})
})
回答by RaphaMex
Now easier to read with async/await
syntax
现在使用async/await
语法更易于阅读
module.exports = async function(tagName) {
const [tag, created] = await Tag.findOrCreate({
where: {tagName},
defaults: {tagName}
});
return tag.get({plain:true});
}
回答by Abdul Vajid
sequelize-values
is an npm-module which helps you do this. It has methods which easily prints the values on both single item and list of results (array)
https://www.npmjs.com/package/sequelize-values
sequelize-values
是一个 npm 模块,它可以帮助你做到这一点。它有方法可以轻松地在单个项目和结果列表(数组)上打印值
https://www.npmjs.com/package/sequelize-values