Sequelize: ¿cómo puedo devolver solo los objetos JSON de los resultados de la base de datos?
Así que quiero que se devuelvan los resultados de la base de datos y nada más. En este momento me devuelven una gran cantidad de datos JSON (como a continuación):
Pero solo necesito el atributo [dataValues]. No quiero tener que usar este poco deJSON
para recuperarlo:tagData[0].dataValues.tagId
.
Acabo de notar: cuando encuentra yNO CREA, devolverá elJSON
para los resultados de la base de datos, pero cuandoNO ENCUENTRA y crea, devuelve el blob JSON innecesario (como a continuación) ¿Hay alguna forma de evitar esto?
[ { 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 ]
En lugar de obtener la gran burbuja como la anterior, solo necesito elRAW
Resultados de json (como a continuación):
{ 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) },
He usado el siguiente javascript. Intenté agregarraw: true
, pero no funcionó?
// 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);
}
});
}
Editar:Así que he investigado un poco y parece que el granJSON
blob solo se devuelve cuandoSequelize
está creando y no encontrando.
¿Hay alguna forma de evitar esto o no?
Edición 2:Bien, he encontrado una solución alternativa, que podría convertirse en una función reutilizable. Pero si hay algo incorporadoSequelize
Prefiero usar eso.
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 })
Edición 3:Por lo tanto, no creo que haya una forma de secuencia "oficial" de lograr esto, así que simplemente escribí un módulo personalizado que devuelve elJSON
datos que se necesitan. ¡Este módulo se puede personalizar y ampliar para adaptarse a diversas situaciones! Si alguien tiene alguna sugerencia sobre cómo se puede mejorar el módulo, no dude en comentar :)
En este módulo estamos devolviendo un objeto Javascript. Si quieres convertirlo enJSON
simplemente encadenarlo usandoJSON.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
}
Edición 4:Entonces, hay un método oficial de secuencia. Consulte la respuesta aceptada a continuación.