sequelize-hierarchy: findAll() does not return simple nested JSON
Maybe I’m doing something wrong or perhaps something broke in recent version of Sequelize. When I run findAll({hiararchy: true}) I don’t get a simple JSON output like what is shown in the example on the front page. I even tried using the attributes keyword to select 3 columns but it still has all the Sequelize meta data. If I use “raw:true” then I get a simple JSON object but there is no nesting.
Model/index.js (from sequelize express example)
"use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var env = process.env.NODE_ENV || "development";
var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
Model
"use strict";
var SequelizeH = require('sequelize-hierarchy')();
module.exports = function(sequelize, Sequelize) {
var Category = sequelize.define('Category', {
name: {
type:Sequelize.STRING,
allowNull: false
}
}, {underscored: true});
Category.isHierarchy();
return Category;
}
findAll
var models = require("../models");
models.Category.findAll({
hierarchy: true,
attributes: ['id','parent_id', 'name']
}).then(function(results) {
console.log(results)
res.render('index', { nested_cat: results });
});
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 18 (6 by maintainers)
Commits related to this issue
- Test for issue #133 — committed to overlookmotel/sequelize-hierarchy by overlookmotel 7 years ago
You need load
hierarchy
before create sequelize instance.If you load
hierarchy(sequelize);
after creating sequelize instancje then it’s not working correctlyAh! Yes that resolved my issue too. Nice work thank you!