Javascript Sequelize-如何仅返回数据库结果的JSON对象?
所以我只想返回数据库结果,别的什么都不想。目前,我得到的是一大块JSON数据(如下所示): 但我只需要[dataValues]属性。我不想使用JSON的this位来检索它:Javascript Sequelize-如何仅返回数据库结果的JSON对象?,javascript,json,sequelize.js,Javascript,Json,Sequelize.js,所以我只想返回数据库结果,别的什么都不想。目前,我得到的是一大块JSON数据(如下所示): 但我只需要[dataValues]属性。我不想使用JSON的this位来检索它:tagData[0].dataValues.tagId 我刚刚注意到:当它找到并且不创建时,它将返回数据库结果的JSON,但是当它没有找到并且创建时,它将返回不需要的JSON blob(如下所示),有办法解决这个问题吗 [ { dataValues: { tagId: 1, tagName: '#has
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 ]
我只需要RAW
json结果(如下所示),而不是像上面那样获取大blob:
我使用了以下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
有没有办法解决这个问题
编辑2:
好的,我找到了一个变通方法,可以转化为一个可重用的函数。但是如果续集中内置了一些东西,我更愿意使用它
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)
对其进行字符串化即可
编辑4:
所以有一个官方的续集方法。请参考下面已接受的答案。如果只想使用,请尝试调用
get({plain:true})
或toJSON()
尽管缺乏文档记录,但这确实存在于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
,它表示是否执行了create查询
2.Sequelize提供了
raw
选项。只需添加选项{raw:true}
,您将只收到原始结果。这将对结果数组起作用,第一种方法不应起作用,因为get
将不是数组的函数。sequelize values
是一个npm模块,可帮助您完成此操作。它具有可以轻松打印单个项目和结果列表(数组)上的值的方法
更新:
使用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=异步函数(标记名){
const[tag,created]=等待tag.findOrCreate({
其中:{tagName},
默认值:{标记名}
});
return tag.get({plain:true});
}
这似乎不起作用。我得到[类型错误:未定义不是函数]
。我想我只需要编写自己的函数来提取普通的JSON
@James111,哦,对不起,尝试在query中不使用raw:true
参数。请确保不要像我刚才那样在列表中询问toJSON()
。问题不是这样,只针对正在搜索的人。这可以用于.findOne()的结果或findAll()的单个对象。在数组中,.toJSON()函数将抛出undefinedThere是一个“官方”的续集方法,请参考我的答案。很好。很抱歉这么晚才接受,我看了一会儿就忘了它有答案。我发布了一个带有async/await
语法的更新,请随时将它集成到您的答案中
tags.findOrCreate( {
where: { tagName: tag }
})
.then(function(tagData){
console.log(tagData.toJSON());
})
Item.findOrCreate({...})
.spread(function(item, created) {
console.log(item.get({
plain: true
})) // logs only the item data, if it was found or created
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'})
})