[英]Sequelize - How can I return JSON objects of the database results only?
所以我只想返回数据库结果,别无其他。 目前我正在返回大量 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 ]
我不需要像上面那样得到大 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) },
我使用了以下 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
blob 仅在Sequelize
正在创建但未找到时才返回。
有没有办法解决这个问题?
好的,所以我找到了一个解决方法,它可以变成一个可重用的函数。 但是,如果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 })
所以,我不认为有实现此目的的“官方”续集方式,所以我只是编写了一个自定义模块来返回所需的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.对于查询产生的任何响应对象,您可以通过在响应中附加.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
不是数组的函数。
如果您只想使用实例的值,请尝试调用get({plain: true})
或toJSON()
tags.findOrCreate( {
where: { tagName: tag }
})
.then(function(tagData){
console.log(tagData.toJSON());
})
更新:
使用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'})
})
现在使用async/await
语法更容易阅读
module.exports = async function(tagName) {
const [tag, created] = await Tag.findOrCreate({
where: {tagName},
defaults: {tagName}
});
return tag.get({plain:true});
}
sequelize-values
是一个 npm 模块,可以帮助你做到这一点。 它有一些方法可以轻松地在单个项目和结果列表(数组)上打印值https://www.npmjs.com/package/sequelize-values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.