Jam*_*111 27 javascript json sequelize.js
所以我想要返回数据库结果而不是别的.目前我收到了大量的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 ]
Run Code Online (Sandbox Code Playgroud)
而不是像上面那样获得大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) },
Run Code Online (Sandbox Code Playgroud)
我使用了以下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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
所以我调查了一下,似乎JSON
只有在Sequelize
创建而不是查找时才会返回大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 })
Run Code Online (Sandbox Code Playgroud)
所以,我认为没有"官方"的续集方式来实现这一点,所以我只是编写了一个自定义模块,它返回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
}
Run Code Online (Sandbox Code Playgroud)
所以有一种官方的续集方法.请参阅下面接受的答案.
ram*_*ssa 25
尽管记录不完整,但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
Run Code Online (Sandbox Code Playgroud)
还要确保spread
为您的动态查询承诺类型使用回调函数.请注意,您可以访问布尔响应,created
表示是否执行了创建查询.
2. Sequelize提供了raw
选项.只需添加选项{raw:true}
,您将只收到原始结果.这将对一组结果起作用,第一种方法不应该,因为它get
不是数组的函数.
如果您只想使用实例的值,请尝试调用get({plain: true})
或toJSON()
tags.findOrCreate( {
where: { tagName: tag }
})
.then(function(tagData){
console.log(tagData.toJSON());
})
Run Code Online (Sandbox Code Playgroud)
更新:
用 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'})
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24377 次 |
最近记录: |