所以我只想返回数据库结果,仅此而已。目前我收到了大量 JSON 数据(如下所示):
但我只需要 [dataValues] 属性。我不想使用这一点 JSON
来检索它:tagData[0].dataValues.tagId
。
我刚刚注意到:当它找到并且 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 ]
我只需要 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) },
我使用了以下 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);
}
});
}
所以我调查了一下,似乎只有当 Sequelize
正在创建而不是找到时才返回大的 JSON
blob。
有没有办法解决这个问题?
好的,我找到了一种解决方法,可以将其转换为可重复使用的功能。但如果 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 })
所以,我认为没有“官方”的 Sequelize 方式来实现这一点,所以我只是编写了一个自定义模块,它返回所需的 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
}
所以有官方的sequelize方法。请参阅下面接受的答案。
最佳答案
尽管记录不充分,但这确实存在于 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
回调函数来处理您的动态查询 promise 类型。请注意,您可以访问 bool 响应 created
,它表示是否执行了创建查询。
2. Sequelize 提供了 raw
选项。只需添加选项 {raw:true}
,您将只收到原始结果。这将适用于结果数组,第一种方法不应该,因为 get
不会是数组的函数。
https://stackoverflow.com/questions/34460482/