속편 - 데이터베이스 결과의 JSON 개체만 반환하려면 어떻게 해야 합니까?
그래서 저는 데이터베이스 결과만 돌려받고 싶습니다.현재 대량의 JSON 데이터가 반환되고 있습니다(아래 참조).
필요한 것은 [dataValues] 속성뿐입니다.이 부분을 사용하고 싶지 않습니다.JSON
가져오려면:tagData[0].dataValues.tagId
.
방금 알아챘어:검색하여 생성하지 않으면 다음 값이 반환됩니다.JSON
데이터베이스 결과를 위해 ITS가 검색하지 않고 생성하면 불필요한 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);
}
});
}
편집:
그래서 제가 조사를 좀 해봤는데 그 큰 문제는JSON
blob이 반환되는 것은Sequelize
만들고 있지만 찾을 수 없습니다.
이 문제를 해결할 방법이 있나요, 없나요?
편집 2:
좋아요, 제가 해결 방법을 찾아냈어요 재사용 가능한 기능으로 바뀔 수도 있어요.하지만 만약 그 안에 뭔가 들어있다면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 })
편집 3:
그래서 저는 이것을 성취하는 "공식" 속편화 방법이 없다고 생각합니다. 그래서 저는 단지 그것을 반환하는 커스텀 모듈을 썼습니다.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
}
편집 4:
그래서 공식적인 속편화 방법이 있다.아래 승인된 답변을 참조하십시오.
문서화는 불충분하지만, 이것은 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. 속편 제작은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-syslog입니다.단일 항목 및 결과 목록(어레이)의 값을 쉽게 인쇄할 수 있는 방법이 있습니다.https://www.npmjs.com/package/sequelize-values
언급URL : https://stackoverflow.com/questions/34460482/sequelize-how-can-i-return-json-objects-of-the-database-results-only
'it-source' 카테고리의 다른 글
JSON을 소독할 필요가 있습니까? (0) | 2023.02.22 |
---|---|
헤더에서 워드프레스 피드 URL을 삭제/제거하는 방법 (0) | 2023.02.22 |
Safari를 통해 허가된 HTTPS 요청이 작동하지 않음 (0) | 2023.02.22 |
Spring Security OAuth2와 Spring Social 통합 (0) | 2023.02.18 |
쇼트 코드 출력 추가쇼트 코드 출력 추가새 줄 뒤에새 줄 뒤에 (0) | 2023.02.16 |